3 require_once("include/template_processor.php");
4 require_once("include/friendica_smarty.php");
5 require_once("include/map.php");
6 require_once("mod/proxy.php");
9 if(! function_exists('replace_macros')) {
11 * This is our template processor
13 * @param string|FriendicaSmarty $s the string requiring macro substitution,
14 * or an instance of FriendicaSmarty
15 * @param array $r key value pairs (search => replace)
16 * @return string substituted string
18 function replace_macros($s,$r) {
20 $stamp1 = microtime(true);
22 // "middleware": inject variables into templates
23 call_hooks("template_vars", $r);
28 $t = $a->template_engine();
30 $output = $t->replace_macros($s,$r);
31 } catch (Exception $e) {
32 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
35 $a->save_timestamp($stamp1, "rendering");
41 // random string, there are 86 characters max in text mode, 128 for hex
44 define('RANDOM_STRING_HEX', 0x00 );
45 define('RANDOM_STRING_TEXT', 0x01 );
47 if(! function_exists('random_string')) {
48 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
49 // generate a bit of entropy and run it through the whirlpool
50 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
51 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
52 return(substr($s,0,$size));
55 if(! function_exists('notags')) {
57 * This is our primary input filter.
59 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
60 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
61 * after cleansing, and angle chars with the high bit set could get through as markup.
63 * This is now disabled because it was interfering with some legitimate unicode sequences
64 * and hopefully there aren't a lot of those browsers left.
66 * Use this on any text input where angle chars are not valid or permitted
67 * They will be replaced with safer brackets. This may be filtered further
68 * if these are not allowed either.
70 * @param string $string Input string
71 * @return string Filtered string
73 function notags($string) {
75 return(str_replace(array("<",">"), array('[',']'), $string));
77 // High-bit filter no longer used
78 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
83 if(! function_exists('escape_tags')) {
85 * use this on "body" or "content" input where angle chars shouldn't be removed,
86 * and allow them to be safely displayed.
87 * @param string $string
90 function escape_tags($string) {
92 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
96 // generate a string that's random, but usually pronounceable.
97 // used to generate initial passwords
99 if(! function_exists('autoname')) {
101 * generate a string that's random, but usually pronounceable.
102 * used to generate initial passwords
106 function autoname($len) {
111 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
112 if(mt_rand(0,5) == 4)
130 's','sc','sh','sm','sp','st',
138 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
139 'nd','ng','nk','nt','rn','rp','rt');
141 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
142 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
144 $start = mt_rand(0,2);
152 for ($x = 0; $x < $len; $x ++) {
153 $r = mt_rand(0,count($table) - 1);
156 if($table == $vowels)
157 $table = array_merge($cons,$midcons);
163 $word = substr($word,0,$len);
165 foreach($noend as $noe) {
166 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
167 $word = substr($word,0,-1);
171 if(substr($word,-1) == 'q')
172 $word = substr($word,0,-1);
177 // escape text ($str) for XML transport
178 // returns escaped text.
180 if(! function_exists('xmlify')) {
182 * escape text ($str) for XML transport
184 * @return string Escaped text.
186 function xmlify($str) {
189 $len = mb_strlen($str);
190 for($x = 0; $x < $len; $x ++) {
191 $char = mb_substr($str,$x,1);
221 $buffer = mb_ereg_replace("&", "&", $str);
222 $buffer = mb_ereg_replace("'", "'", $buffer);
223 $buffer = mb_ereg_replace('"', """, $buffer);
224 $buffer = mb_ereg_replace("<", "<", $buffer);
225 $buffer = mb_ereg_replace(">", ">", $buffer);
227 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
228 $buffer = trim($buffer);
233 if(! function_exists('unxmlify')) {
236 * @param string $s xml escaped text
237 * @return string unescaped text
239 function unxmlify($s) {
240 // $ret = str_replace('&','&', $s);
241 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
242 /*$ret = mb_ereg_replace('&', '&', $s);
243 $ret = mb_ereg_replace(''', "'", $ret);
244 $ret = mb_ereg_replace('"', '"', $ret);
245 $ret = mb_ereg_replace('<', "<", $ret);
246 $ret = mb_ereg_replace('>', ">", $ret);
248 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
252 if(! function_exists('hex2bin')) {
254 * convenience wrapper, reverse the operation "bin2hex"
258 function hex2bin($s) {
259 if(! (is_string($s) && strlen($s)))
262 if(! ctype_xdigit($s)) {
266 return(pack("H*",$s));
270 if(! function_exists('paginate_data')) {
272 * Automatica pagination data.
274 * @param App $a App instance
275 * @param int $count [optional] item count (used with alt pager)
276 * @return Array data for pagination template
278 function paginate_data(&$a, $count=null) {
279 $stripped = preg_replace('/([&?]page=[0-9]*)/','',$a->query_string);
281 $stripped = str_replace('q=','',$stripped);
282 $stripped = trim($stripped,'/');
283 $pagenum = $a->pager['page'];
285 if (($a->page_offset != "") AND !preg_match('/[?&].offset=/', $stripped))
286 $stripped .= "&offset=".urlencode($a->page_offset);
288 $url = $a->get_baseurl() . '/' . $stripped;
291 function _l(&$d, $name, $url, $text, $class="") {
292 if (!strpos($url, "?")) {
293 if ($pos = strpos($url, "&"))
294 $url = substr($url, 0, $pos)."?".substr($url, $pos + 1);
297 $d[$name] = array('url'=>$url, 'text'=>$text, 'class'=>$class);
300 if (!is_null($count)){
302 if($a->pager['page']>1)
303 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('newer'));
305 _l($data, "next", $url.'&page='.($a->pager['page'] + 1), t('older'));
308 if($a->pager['total'] > $a->pager['itemspage']) {
309 if($a->pager['page'] != 1)
310 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('prev'));
312 _l($data, "first", $url."&page=1", t('first'));
315 $numpages = $a->pager['total'] / $a->pager['itemspage'];
318 $numstop = $numpages;
321 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
322 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
327 for($i = $numstart; $i <= $numstop; $i++){
328 if($i == $a->pager['page'])
329 _l($pages, $i, "#", $i, "current");
331 _l($pages, $i, $url."&page=$i", $i, "n");
334 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
335 if($i == $a->pager['page'])
336 _l($pages, $i, "#", $i, "current");
338 _l($pages, $i, $url."&page=$i", $i, "n");
341 $data['pages'] = $pages;
343 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
344 _l($data, "last", $url."&page=$lastpage", t('last'));
346 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
347 _l($data, "next", $url."&page=".($a->pager['page'] + 1), t('next'));
355 if(! function_exists('paginate')) {
357 * Automatic pagination.
359 * To use, get the count of total items.
360 * Then call $a->set_pager_total($number_items);
361 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
362 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
363 * (assuming there are enough items to paginate).
364 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
365 * will limit the results to the correct items for the current page.
366 * The actual page handling is then accomplished at the application layer.
368 * @param App $a App instance
369 * @return string html for pagination #FIXME remove html
371 function paginate(&$a) {
373 $data = paginate_data($a);
374 $tpl = get_markup_template("paginate.tpl");
375 return replace_macros($tpl, array("pager" => $data));
379 if(! function_exists('alt_pager')) {
382 * @param App $a App instance
384 * @return string html for pagination #FIXME remove html
386 function alt_pager(&$a, $i) {
388 $data = paginate_data($a, $i);
389 $tpl = get_markup_template("paginate.tpl");
390 return replace_macros($tpl, array('pager' => $data));
394 if(! function_exists('scroll_loader')) {
396 * Loader for infinite scrolling
397 * @return string html for loader
399 function scroll_loader() {
400 $tpl = get_markup_template("scroll_loader.tpl");
401 return replace_macros($tpl, array(
402 'wait' => t('Loading more entries...'),
403 'end' => t('The end')
407 if(! function_exists('expand_acl')) {
409 * Turn user/group ACLs stored as angle bracketed text into arrays
414 function expand_acl($s) {
415 // turn string array of angle-bracketed elements into numeric array
416 // e.g. "<1><2><3>" => array(1,2,3);
420 $t = str_replace('<','',$s);
421 $a = explode('>',$t);
424 $ret[] = intval($aa);
430 if(! function_exists('sanitise_acl')) {
432 * Wrap ACL elements in angle brackets for storage
433 * @param string $item
435 function sanitise_acl(&$item) {
437 $item = '<' . intval(notags(trim($item))) . '>';
443 if(! function_exists('perms2str')) {
445 * Convert an ACL array to a storable string
447 * Normally ACL permissions will be an array.
448 * We'll also allow a comma-separated string.
450 * @param string|array $p
453 function perms2str($p) {
458 $tmp = explode(',',$p);
461 array_walk($tmp,'sanitise_acl');
462 $ret = implode('',$tmp);
468 if(! function_exists('item_new_uri')) {
470 * generate a guaranteed unique (for this domain) item ID for ATOM
471 * safe from birthday paradox
473 * @param string $hostname
477 function item_new_uri($hostname,$uid, $guid = "") {
483 $hash = get_guid(32);
489 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
491 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
495 } while($dups == true);
499 // Generate a guaranteed unique photo ID.
500 // safe from birthday paradox
502 if(! function_exists('photo_new_resource')) {
504 * Generate a guaranteed unique photo ID.
505 * safe from birthday paradox
509 function photo_new_resource() {
513 $resource = hash('md5',uniqid(mt_rand(),true));
514 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
519 } while($found == true);
524 if(! function_exists('load_view_file')) {
527 * wrapper to load a view template, checking for alternate
528 * languages before falling back to the default
530 * @global string $lang
532 * @param string $s view name
535 function load_view_file($s) {
541 if(file_exists("$d/$lang/$b")) {
542 $stamp1 = microtime(true);
543 $content = file_get_contents("$d/$lang/$b");
544 $a->save_timestamp($stamp1, "file");
548 $theme = current_theme();
550 if(file_exists("$d/theme/$theme/$b")) {
551 $stamp1 = microtime(true);
552 $content = file_get_contents("$d/theme/$theme/$b");
553 $a->save_timestamp($stamp1, "file");
557 $stamp1 = microtime(true);
558 $content = file_get_contents($s);
559 $a->save_timestamp($stamp1, "file");
563 if(! function_exists('get_intltext_template')) {
565 * load a view template, checking for alternate
566 * languages before falling back to the default
568 * @global string $lang
569 * @param string $s view path
572 function get_intltext_template($s) {
577 if($a->theme['template_engine'] === 'smarty3')
578 $engine = "/smarty3";
583 if(file_exists("view/$lang$engine/$s")) {
584 $stamp1 = microtime(true);
585 $content = file_get_contents("view/$lang$engine/$s");
586 $a->save_timestamp($stamp1, "file");
588 } elseif(file_exists("view/en$engine/$s")) {
589 $stamp1 = microtime(true);
590 $content = file_get_contents("view/en$engine/$s");
591 $a->save_timestamp($stamp1, "file");
594 $stamp1 = microtime(true);
595 $content = file_get_contents("view$engine/$s");
596 $a->save_timestamp($stamp1, "file");
601 if(! function_exists('get_markup_template')) {
606 * @param string $root
609 function get_markup_template($s, $root = '') {
610 $stamp1 = microtime(true);
613 $t = $a->template_engine();
615 $template = $t->get_template_file($s, $root);
616 } catch (Exception $e) {
617 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
620 $a->save_timestamp($stamp1, "file");
625 if(! function_exists("get_template_file")) {
629 * @param string $filename
630 * @param string $root
633 function get_template_file($a, $filename, $root = '') {
634 $theme = current_theme();
636 // Make sure $root ends with a slash /
637 if($root !== '' && $root[strlen($root)-1] !== '/')
640 if(file_exists("{$root}view/theme/$theme/$filename"))
641 $template_file = "{$root}view/theme/$theme/$filename";
642 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
643 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
644 elseif (file_exists("{$root}/$filename"))
645 $template_file = "{$root}/$filename";
647 $template_file = "{$root}view/$filename";
649 return $template_file;
658 if(! function_exists('attribute_contains')) {
660 * for html,xml parsing - let's say you've got
661 * an attribute foobar="class1 class2 class3"
662 * and you want to find out if it contains 'class3'.
663 * you can't use a normal sub string search because you
664 * might match 'notclass3' and a regex to do the job is
665 * possible but a bit complicated.
666 * pass the attribute string as $attr and the attribute you
667 * are looking for as $s - returns true if found, otherwise false
669 * @param string $attr attribute value
670 * @param string $s string to search
671 * @return boolean True if found, False otherwise
673 function attribute_contains($attr,$s) {
674 $a = explode(' ', $attr);
675 if(count($a) && in_array($s,$a))
680 if(! function_exists('logger')) {
681 /* setup int->string log level map */
682 $LOGGER_LEVELS = array();
686 * LOGGER_NORMAL (default)
697 function logger($msg,$level = 0) {
698 // turn off logger in install mode
701 global $LOGGER_LEVELS;
703 if(($a->module == 'install') || (! ($db && $db->connected))) return;
705 if (count($LOGGER_LEVELS)==0){
706 foreach (get_defined_constants() as $k=>$v){
707 if (substr($k,0,7)=="LOGGER_")
708 $LOGGER_LEVELS[$v] = substr($k,7,7);
712 $debugging = get_config('system','debugging');
713 $loglevel = intval(get_config('system','loglevel'));
714 $logfile = get_config('system','logfile');
716 if((! $debugging) || (! $logfile) || ($level > $loglevel))
719 $callers = debug_backtrace();
720 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
723 $LOGGER_LEVELS[$level],
724 basename($callers[0]['file']),
726 $callers[1]['function'],
730 $stamp1 = microtime(true);
731 @file_put_contents($logfile, $logline, FILE_APPEND);
732 $a->save_timestamp($stamp1, "file");
737 if(! function_exists('activity_match')) {
739 * Compare activity uri. Knows about activity namespace.
741 * @param string $haystack
742 * @param string $needle
745 function activity_match($haystack,$needle) {
746 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
752 if(! function_exists('get_tags')) {
754 * Pull out all #hashtags and @person tags from $s;
755 * We also get @person@domain.com - which would make
756 * the regex quite complicated as tags can also
757 * end a sentence. So we'll run through our results
758 * and strip the period from any tags which end with one.
759 * Returns array of tags found, or empty array.
764 function get_tags($s) {
767 // Convert hashtag links to hashtags
768 $s = preg_replace("/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism", "#$2", $s);
770 // ignore anything in a code block
771 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
773 // Force line feeds at bbtags
774 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
776 // ignore anything in a bbtag
777 $s = preg_replace('/\[(.*?)\]/sm','',$s);
779 // Match full names against @tags including the space between first and last
780 // We will look these up afterward to see if they are full names or not recognisable.
782 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
783 foreach($match[1] as $mtch) {
784 if(strstr($mtch,"]")) {
785 // we might be inside a bbcode color tag - leave it alone
788 if(substr($mtch,-1,1) === '.')
789 $ret[] = substr($mtch,0,-1);
795 // Otherwise pull out single word tags. These can be @nickname, @first_last
798 if(preg_match_all('/([!#@][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
799 foreach($match[1] as $mtch) {
800 if(strstr($mtch,"]")) {
801 // we might be inside a bbcode color tag - leave it alone
804 if(substr($mtch,-1,1) === '.')
805 $mtch = substr($mtch,0,-1);
806 // ignore strictly numeric tags like #1
807 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
809 // try not to catch url fragments
810 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
821 if(! function_exists('qp')) {
823 * quick and dirty quoted_printable encoding
829 return str_replace ("%","=",rawurlencode($s));
834 if(! function_exists('get_mentions')) {
837 * @return string html for mentions #FIXME: remove html
839 function get_mentions($item) {
841 if(! strlen($item['tag']))
844 $arr = explode(',',$item['tag']);
845 foreach($arr as $x) {
847 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
848 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
849 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
853 if (!$item['private']) {
854 $o .= "\t\t".'<link rel="ostatus:attention" href="http://activityschema.org/collection/public"/>'."\r\n";
855 $o .= "\t\t".'<link rel="mentioned" href="http://activityschema.org/collection/public"/>'."\r\n";
861 if(! function_exists('contact_block')) {
863 * Get html for contact block.
865 * @template contact_block.tpl
866 * @hook contact_block_end (contacts=>array, output=>string)
869 function contact_block() {
873 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
879 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
881 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
882 WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0
883 AND `hidden` = 0 AND `archive` = 0
884 AND `network` IN ('%s', '%s', '%s')",
885 intval($a->profile['uid']),
887 dbesc(NETWORK_OSTATUS),
888 dbesc(NETWORK_DIASPORA)
891 $total = intval($r[0]['total']);
894 $contacts = t('No contacts');
898 $r = q("SELECT * FROM `contact`
899 WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0
900 AND `hidden` = 0 AND `archive` = 0
901 AND `network` IN ('%s', '%s', '%s') ORDER BY RAND() LIMIT %d",
902 intval($a->profile['uid']),
904 dbesc(NETWORK_OSTATUS),
905 dbesc(NETWORK_DIASPORA),
909 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
912 $micropro[] = micropro($rr,true,'mpfriend');
917 $tpl = get_markup_template('contact_block.tpl');
918 $o = replace_macros($tpl, array(
919 '$contacts' => $contacts,
920 '$nickname' => $a->profile['nickname'],
921 '$viewcontacts' => t('View Contacts'),
922 '$micropro' => $micropro,
925 $arr = array('contacts' => $r, 'output' => $o);
927 call_hooks('contact_block_end', $arr);
932 if(! function_exists('micropro')) {
935 * @param array $contact
936 * @param boolean $redirect
937 * @param string $class
938 * @param boolean $textmode
939 * @return string #FIXME: remove html
941 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
944 $class = ' ' . $class;
946 $url = $contact['url'];
952 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
953 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
955 $url = $redirect_url;
956 $sparkle = ' sparkle';
961 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
965 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
966 . (($click) ? ' fakelink' : '') . '" '
967 . (($redir) ? ' target="redir" ' : '')
968 . (($url) ? ' href="' . $url . '"' : '') . $click
969 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
970 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
973 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
974 . (($click) ? ' fakelink' : '') . '" '
975 . (($redir) ? ' target="redir" ' : '')
976 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
977 . proxy_url($contact['micro'], false, PROXY_SIZE_THUMB) . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
978 . '" /></a></div>' . "\r\n";
984 if(! function_exists('search')) {
988 * @param string $s search query
989 * @param string $id html id
990 * @param string $url search url
991 * @param boolean $savedsearch show save search button
993 function search($s,$id='search-box',$url='/search',$save = false, $aside = true) {
999 '$action_url' => $a->get_baseurl((stristr($url,'network')) ? true : false) . $url,
1000 '$search_label' => t('Search'),
1001 '$save_label' => t('Save'),
1002 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1006 $values['$searchoption'] = array(
1011 if (get_config('system','poco_local_search'))
1012 $values['$searchoption'][] = t("Forums");
1015 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1018 if(! function_exists('valid_email')) {
1020 * Check if $x is a valid email string
1025 function valid_email($x){
1027 if(get_config('system','disable_email_validation'))
1030 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
1036 if(! function_exists('linkify')) {
1038 * Replace naked text hyperlink with HTML formatted hyperlink
1042 function linkify($s) {
1043 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1044 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1052 * @return array index is present tense verb
1053 value is array containing past tense verb, translation of present, translation of past
1054 * @hook poke_verbs pokes array
1056 function get_poke_verbs() {
1058 // index is present tense verb
1059 // value is array containing past tense verb, translation of present, translation of past
1062 'poke' => array( 'poked', t('poke'), t('poked')),
1063 'ping' => array( 'pinged', t('ping'), t('pinged')),
1064 'prod' => array( 'prodded', t('prod'), t('prodded')),
1065 'slap' => array( 'slapped', t('slap'), t('slapped')),
1066 'finger' => array( 'fingered', t('finger'), t('fingered')),
1067 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1069 call_hooks('poke_verbs', $arr);
1075 * @return array index is mood, value is translated mood
1076 * @hook mood_verbs moods array
1078 function get_mood_verbs() {
1081 'happy' => t('happy'),
1083 'mellow' => t('mellow'),
1084 'tired' => t('tired'),
1085 'perky' => t('perky'),
1086 'angry' => t('angry'),
1087 'stupefied' => t('stupified'),
1088 'puzzled' => t('puzzled'),
1089 'interested' => t('interested'),
1090 'bitter' => t('bitter'),
1091 'cheerful' => t('cheerful'),
1092 'alive' => t('alive'),
1093 'annoyed' => t('annoyed'),
1094 'anxious' => t('anxious'),
1095 'cranky' => t('cranky'),
1096 'disturbed' => t('disturbed'),
1097 'frustrated' => t('frustrated'),
1098 'motivated' => t('motivated'),
1099 'relaxed' => t('relaxed'),
1100 'surprised' => t('surprised'),
1103 call_hooks('mood_verbs', $arr);
1109 if(! function_exists('smilies')) {
1111 * Replaces text emoticons with graphical images
1113 * It is expected that this function will be called using HTML text.
1114 * We will escape text between HTML pre and code blocks from being
1117 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
1118 * function from being executed by the prepare_text() routine when preparing
1119 * bbcode source for HTML display
1122 * @param boolean $sample
1124 * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1126 function smilies($s, $sample = false) {
1129 if(intval(get_config('system','no_smilies'))
1130 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1133 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1134 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1176 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1177 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1178 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1179 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1180 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1181 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1182 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1183 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1184 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1185 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1186 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1187 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1188 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1189 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1190 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1191 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
1192 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
1193 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
1194 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
1195 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
1196 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1197 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1198 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1199 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1200 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1201 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1202 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1203 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1204 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1205 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1206 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1207 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1208 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
1209 '<a href="http://redmatrix.me/">red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="red" />matrix</a>',
1210 '<a href="http://redmatrix.me/">red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="red" />matrix</a>'
1213 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1214 call_hooks('smilie', $params);
1217 $s = '<div class="smiley-sample">';
1218 for($x = 0; $x < count($params['texts']); $x ++) {
1219 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1223 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
1224 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1227 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1228 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1234 function smile_encode($m) {
1235 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1238 function smile_decode($m) {
1239 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1244 * expand <3333 to the correct number of hearts
1249 function preg_heart($x) {
1251 if(strlen($x[1]) == 1)
1254 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1255 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1256 $r = str_replace($x[0],$t,$x[0]);
1261 if(! function_exists('day_translate')) {
1263 * Translate days and months names
1268 function day_translate($s) {
1269 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1270 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1273 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1274 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')),
1281 if(! function_exists('normalise_link')) {
1285 * @param string $url
1288 function normalise_link($url) {
1289 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1290 return(rtrim($ret,'/'));
1295 if(! function_exists('link_compare')) {
1297 * Compare two URLs to see if they are the same, but ignore
1298 * slight but hopefully insignificant differences such as if one
1299 * is https and the other isn't, or if one is www.something and
1300 * the other isn't - and also ignore case differences.
1302 * @param string $a first url
1303 * @param string $b second url
1304 * @return boolean True if the URLs match, otherwise False
1307 function link_compare($a,$b) {
1308 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1314 if(! function_exists('redir_private_images')) {
1316 * Find any non-embedded images in private items and add redir links to them
1319 * @param array $item
1321 function redir_private_images($a, &$item) {
1324 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1326 //logger("redir_private_images: matches = " . print_r($matches, true));
1327 foreach($matches as $mtch) {
1328 if(strpos($mtch[1], '/redir') !== false)
1331 if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1332 //logger("redir_private_images: redir");
1333 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1334 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1341 function put_item_in_cache(&$item, $update = false) {
1343 if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
1344 ($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
1346 // The function "redir_private_images" changes the body.
1347 // I'm not sure if we should store it permanently, so we save the old value.
1348 $body = $item["body"];
1351 redir_private_images($a, $item);
1353 $item["rendered-html"] = prepare_text($item["body"]);
1354 $item["rendered-hash"] = hash("md5", $item["body"]);
1355 $item["body"] = $body;
1357 if ($update AND ($item["id"] != 0)) {
1358 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1359 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1364 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1365 // If attach is true, also add icons for item attachments
1367 if(! function_exists('prepare_body')) {
1369 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1370 * If attach is true, also add icons for item attachments
1372 * @param array $item
1373 * @param boolean $attach
1374 * @return string item body html
1375 * @hook prepare_body_init item array before any work
1376 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1377 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1379 function prepare_body(&$item,$attach = false, $preview = false) {
1382 call_hooks('prepare_body_init', $item);
1384 $searchpath = $a->get_baseurl()."/search?tag=";
1387 $hashtags = array();
1388 $mentions = array();
1390 if (!get_config('system','suppress_tags')) {
1391 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1392 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1394 foreach($taglist as $tag) {
1396 if ($tag["url"] == "")
1397 $tag["url"] = $searchpath.strtolower($tag["term"]);
1399 if ($tag["type"] == TERM_HASHTAG) {
1400 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1402 } elseif ($tag["type"] == TERM_MENTION) {
1403 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1406 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1410 $item['tags'] = $tags;
1411 $item['hashtags'] = $hashtags;
1412 $item['mentions'] = $mentions;
1414 put_item_in_cache($item, true);
1415 $s = $item["rendered-html"];
1417 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1418 call_hooks('prepare_body', $prep_arr);
1419 $s = $prep_arr['html'];
1422 // Replace the blockquotes with quotes that are used in mails
1423 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1424 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1430 $arr = explode('[/attach],',$item['attach']);
1432 $as .= '<div class="body-attach">';
1433 foreach($arr as $r) {
1436 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1438 foreach($matches as $mtch) {
1441 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1442 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1444 $the_url = $mtch[1];
1446 if(strpos($mime, 'video') !== false) {
1449 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1450 '$baseurl' => $a->get_baseurl(),
1452 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1453 '$baseurl' => $a->get_baseurl(),
1457 $id = end(explode('/', $the_url));
1458 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1461 'title' => t('View Video'),
1468 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1470 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1471 $filesubtype = str_replace('.', '-', $filesubtype);
1475 $filesubtype = 'unkn';
1478 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1479 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1485 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1488 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1492 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1493 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1495 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1499 $as .= '<div class="clear"></div></div>';
1504 if(strpos($s,'<div class="map">') !== false && $item['coord']) {
1505 $x = generate_map(trim($item['coord']));
1507 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1513 $spoilersearch = '<blockquote class="spoiler">';
1515 // Remove line breaks before the spoiler
1516 while ((strpos($s, "\n".$spoilersearch) !== false))
1517 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1518 while ((strpos($s, "<br />".$spoilersearch) !== false))
1519 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1521 while ((strpos($s, $spoilersearch) !== false)) {
1523 $pos = strpos($s, $spoilersearch);
1524 $rnd = random_string(8);
1525 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1526 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1527 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1530 // Look for quote with author
1531 $authorsearch = '<blockquote class="author">';
1533 while ((strpos($s, $authorsearch) !== false)) {
1535 $pos = strpos($s, $authorsearch);
1536 $rnd = random_string(8);
1537 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1538 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1539 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1542 // replace friendica image url size with theme preference
1543 if (x($a->theme_info,'item_image_size')){
1544 $ps = $a->theme_info['item_image_size'];
1546 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
1549 $prep_arr = array('item' => $item, 'html' => $s);
1550 call_hooks('prepare_body_final', $prep_arr);
1552 return $prep_arr['html'];
1556 if(! function_exists('prepare_text')) {
1558 * Given a text string, convert from bbcode to html and add smilie icons.
1560 * @param string $text
1563 function prepare_text($text) {
1565 require_once('include/bbcode.php');
1567 if(stristr($text,'[nosmile]'))
1570 $s = smilies(bbcode($text));
1578 * return array with details for categories and folders for an item
1580 * @param array $item
1584 * [ // categories array
1586 * 'name': 'category name',
1587 * 'removeurl': 'url to remove this category',
1588 * 'first': 'is the first in this array? true/false',
1589 * 'last': 'is the last in this array? true/false',
1595 * 'name': 'folder name',
1596 * 'removeurl': 'url to remove this folder',
1597 * 'first': 'is the first in this array? true/false',
1598 * 'last': 'is the last in this array? true/false',
1604 function get_cats_and_terms($item) {
1607 $categories = array();
1610 $matches = false; $first = true;
1611 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1613 foreach($matches as $mtch) {
1614 $categories[] = array(
1615 'name' => xmlify(file_tag_decode($mtch[1])),
1617 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1624 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1627 if(local_user() == $item['uid']) {
1628 $matches = false; $first = true;
1629 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1631 foreach($matches as $mtch) {
1633 'name' => xmlify(file_tag_decode($mtch[1])),
1635 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1644 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1646 return array($categories, $folders);
1651 if(! function_exists('feed_hublinks')) {
1653 * return atom link elements for all of our hubs
1654 * @return string hub link xml elements
1656 function feed_hublinks() {
1658 $hub = get_config('system','huburl');
1662 $hubs = explode(',', $hub);
1664 foreach($hubs as $h) {
1668 if ($h === '[internal]')
1669 $h = $a->get_baseurl() . '/pubsubhubbub';
1670 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1678 if(! function_exists('feed_salmonlinks')) {
1680 * return atom link elements for salmon endpoints
1681 * @param string $nick user nickname
1682 * @return string salmon link xml elements
1684 function feed_salmonlinks($nick) {
1688 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1690 // old style links that status.net still needed as of 12/2010
1692 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1693 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1697 if(! function_exists('get_plink')) {
1699 * get private link for item
1700 * @param array $item
1701 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1703 function get_plink($item) {
1706 if ($a->user['nickname'] != "") {
1708 //'href' => $a->get_baseurl()."/display/".$a->user['nickname']."/".$item['id'],
1709 'href' => $a->get_baseurl()."/display/".$item['guid'],
1710 'orig' => $a->get_baseurl()."/display/".$item['guid'],
1711 'title' => t('View on separate page'),
1712 'orig_title' => t('view on separate page'),
1715 if (x($item,'plink')) {
1716 $ret["href"] = $item['plink'];
1717 $ret["title"] = t('link to source');
1720 } elseif (x($item,'plink') && ($item['private'] != 1))
1722 'href' => $item['plink'],
1723 'orig' => $item['plink'],
1724 'title' => t('link to source'),
1729 //if (x($item,'plink') && ($item['private'] != 1))
1734 if(! function_exists('unamp')) {
1736 * replace html amp entity with amp char
1740 function unamp($s) {
1741 return str_replace('&', '&', $s);
1747 if(! function_exists('lang_selector')) {
1749 * get html for language selector
1750 * @global string $lang
1752 * @template lang_selector.tpl
1754 function lang_selector() {
1757 $langs = glob('view/*/strings.php');
1759 $lang_options = array();
1762 if(is_array($langs) && count($langs)) {
1764 if(! in_array('view/en/strings.php',$langs))
1765 $langs[] = 'view/en/';
1767 foreach($langs as $l) {
1769 $lang_options[""] = t('default');
1773 $ll = substr($ll,0,strrpos($ll,'/'));
1774 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1775 $lang_options[$ll]=$ll;
1779 $tpl = get_markup_template("lang_selector.tpl");
1780 $o = replace_macros($tpl, array(
1781 '$title' => t('Select an alternate language'),
1782 '$langs' => array($lang_options, $selected),
1789 if(! function_exists('return_bytes')) {
1791 * return number of bytes in size (K, M, G)
1792 * @param string $size_str
1795 function return_bytes ($size_str) {
1796 switch (substr ($size_str, -1))
1798 case 'M': case 'm': return (int)$size_str * 1048576;
1799 case 'K': case 'k': return (int)$size_str * 1024;
1800 case 'G': case 'g': return (int)$size_str * 1073741824;
1801 default: return $size_str;
1808 function generate_user_guid() {
1811 $guid = get_guid(32);
1812 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1817 } while ($found == true );
1824 * @param boolean $strip_padding
1827 function base64url_encode($s, $strip_padding = false) {
1829 $s = strtr(base64_encode($s),'+/','-_');
1832 $s = str_replace('=','',$s);
1841 function base64url_decode($s) {
1844 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1849 * // Placeholder for new rev of salmon which strips base64 padding.
1850 * // PHP base64_decode handles the un-padded input without requiring this step
1851 * // Uncomment if you find you need it.
1854 * if(! strpos($s,'=')) {
1864 return base64_decode(strtr($s,'-_','+/'));
1868 if (!function_exists('str_getcsv')) {
1872 * @param string $input
1873 * @param string $delimiter
1874 * @param string $enclosure
1875 * @param string $escape
1876 * @param string $eol
1877 * @return boolean|array False on error, otherwise array[row][column]
1879 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1880 if (is_string($input) && !empty($input)) {
1882 $tmp = preg_split("/".$eol."/",$input);
1883 if (is_array($tmp) && !empty($tmp)) {
1884 while (list($line_num, $line) = each($tmp)) {
1885 if (preg_match("/".$escape.$enclosure."/",$line)) {
1886 while ($strlen = strlen($line)) {
1887 $pos_delimiter = strpos($line,$delimiter);
1888 $pos_enclosure_start = strpos($line,$enclosure);
1890 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1891 && ($pos_enclosure_start < $pos_delimiter)
1893 $enclosed_str = substr($line,1);
1894 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1895 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1896 $output[$line_num][] = $enclosed_str;
1897 $offset = $pos_enclosure_end+3;
1899 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1900 $output[$line_num][] = substr($line,0);
1901 $offset = strlen($line);
1903 $output[$line_num][] = substr($line,0,$pos_delimiter);
1905 !empty($pos_enclosure_start)
1906 && ($pos_enclosure_start < $pos_delimiter)
1908 ?$pos_enclosure_start
1912 $line = substr($line,$offset);
1915 $line = preg_split("/".$delimiter."/",$line);
1918 * Validating against pesky extra line breaks creating false rows.
1920 if (is_array($line) && !empty($line[0])) {
1921 $output[$line_num] = $line;
1936 * return div element with class 'clear'
1940 function cleardiv() {
1941 return '<div class="clear"></div>';
1945 function bb_translate_video($s) {
1948 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1950 foreach($matches as $mtch) {
1951 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1952 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1953 elseif(stristr($mtch[1],'vimeo'))
1954 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1960 function html2bb_video($s) {
1962 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1963 '[youtube]$2[/youtube]', $s);
1965 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1966 '[youtube]$2[/youtube]', $s);
1968 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1969 '[vimeo]$2[/vimeo]', $s);
1975 * apply xmlify() to all values of array $val, recursively
1979 function array_xmlify($val){
1980 if (is_bool($val)) return $val?"true":"false";
1981 if (is_array($val)) return array_map('array_xmlify', $val);
1982 return xmlify((string) $val);
1987 * transorm link href and img src from relative to absolute
1989 * @param string $text
1990 * @param string $base base url
1993 function reltoabs($text, $base)
1998 $base = rtrim($base,'/');
2000 $base2 = $base . "/";
2003 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
2004 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
2005 $text = preg_replace($pattern, $replace, $text);
2007 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
2008 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
2009 $text = preg_replace($pattern, $replace, $text);
2012 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
2013 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
2014 $text = preg_replace($pattern, $replace, $text);
2016 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
2017 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
2018 $text = preg_replace($pattern, $replace, $text);
2026 * get translated item type
2028 * @param array $itme
2031 function item_post_type($item) {
2032 if(intval($item['event-id']))
2034 if(strlen($item['resource-id']))
2036 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
2037 return t('activity');
2038 if($item['id'] != $item['parent'])
2039 return t('comment');
2043 // post categories and "save to file" use the same item.file table for storage.
2044 // We will differentiate the different uses by wrapping categories in angle brackets
2045 // and save to file categories in square brackets.
2046 // To do this we need to escape these characters if they appear in our tag.
2048 function file_tag_encode($s) {
2049 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
2052 function file_tag_decode($s) {
2053 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
2056 function file_tag_file_query($table,$s,$type = 'file') {
2059 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
2061 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
2062 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
2065 // ex. given music,video return <music><video> or [music][video]
2066 function file_tag_list_to_file($list,$type = 'file') {
2069 $list_array = explode(",",$list);
2070 if($type == 'file') {
2079 foreach($list_array as $item) {
2081 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
2088 // ex. given <music><video>[friends], return music,video or friends
2089 function file_tag_file_to_list($file,$type = 'file') {
2092 if($type == 'file') {
2093 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
2096 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
2099 foreach($matches as $mtch) {
2102 $list .= file_tag_decode($mtch[1]);
2109 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
2110 // $file_old - categories previously associated with an item
2111 // $file_new - new list of categories for an item
2116 if($file_old == $file_new)
2119 $saved = get_pconfig($uid,'system','filetags');
2120 if(strlen($saved)) {
2121 if($type == 'file') {
2124 $termtype = TERM_FILE;
2129 $termtype = TERM_CATEGORY;
2132 $filetags_updated = $saved;
2134 // check for new tags to be added as filetags in pconfig
2135 $new_tags = array();
2136 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2138 foreach($check_new_tags as $tag) {
2139 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2143 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2145 // check for deleted tags to be removed from filetags in pconfig
2146 $deleted_tags = array();
2147 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2149 foreach($check_deleted_tags as $tag) {
2150 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2151 $deleted_tags[] = $tag;
2154 foreach($deleted_tags as $key => $tag) {
2155 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2157 intval(TERM_OBJ_POST),
2161 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2166 unset($deleted_tags[$key]);
2169 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2173 if($saved != $filetags_updated) {
2174 set_pconfig($uid,'system','filetags', $filetags_updated);
2179 if(strlen($file_new)) {
2180 set_pconfig($uid,'system','filetags', $file_new);
2185 function file_tag_save_file($uid,$item,$file) {
2186 require_once("include/files.php");
2191 $r = q("select file from item where id = %d and uid = %d limit 1",
2196 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2197 q("update item set file = '%s' where id = %d and uid = %d",
2198 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2203 create_files_from_item($item);
2205 $saved = get_pconfig($uid,'system','filetags');
2206 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2207 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2208 info( t('Item filed') );
2213 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2214 require_once("include/files.php");
2221 $pattern = '<' . file_tag_encode($file) . '>' ;
2222 $termtype = TERM_CATEGORY;
2224 $pattern = '[' . file_tag_encode($file) . ']' ;
2225 $termtype = TERM_FILE;
2229 $r = q("select file from item where id = %d and uid = %d limit 1",
2236 q("update item set file = '%s' where id = %d and uid = %d",
2237 dbesc(str_replace($pattern,'',$r[0]['file'])),
2242 create_files_from_item($item);
2244 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2246 intval(TERM_OBJ_POST),
2250 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2254 $saved = get_pconfig($uid,'system','filetags');
2255 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2261 function normalise_openid($s) {
2262 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2266 function undo_post_tagging($s) {
2268 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2270 foreach($matches as $mtch) {
2271 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2277 function fix_mce_lf($s) {
2278 $s = str_replace("\r\n","\n",$s);
2279 // $s = str_replace("\n\n","\n",$s);
2284 function protect_sprintf($s) {
2285 return(str_replace('%','%%',$s));
2289 function is_a_date_arg($s) {
2293 if($i <= $y+1 && strpos($s,'-') == 4) {
2294 $m = intval(substr($s,5));
2295 if($m > 0 && $m <= 12)
2303 * remove intentation from a text
2305 function deindent($text, $chr="[\t ]", $count=NULL) {
2306 $text = fix_mce_lf($text);
2307 $lines = explode("\n", $text);
2308 if (is_null($count)) {
2310 $k=0; while($k<count($lines) && strlen($lines[$k])==0) $k++;
2311 preg_match("|^".$chr."*|", $lines[$k], $m);
2312 $count = strlen($m[0]);
2314 for ($k=0; $k<count($lines); $k++){
2315 $lines[$k] = preg_replace("|^".$chr."{".$count."}|", "", $lines[$k]);
2318 return implode("\n", $lines);
2321 function formatBytes($bytes, $precision = 2) {
2322 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2324 $bytes = max($bytes, 0);
2325 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2326 $pow = min($pow, count($units) - 1);
2328 $bytes /= pow(1024, $pow);
2330 return round($bytes, $precision) . ' ' . $units[$pow];