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);
24 $t = $a->template_engine();
26 $output = $t->replace_macros($s,$r);
27 } catch (Exception $e) {
28 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
31 $a->save_timestamp($stamp1, "rendering");
37 // random string, there are 86 characters max in text mode, 128 for hex
40 define('RANDOM_STRING_HEX', 0x00 );
41 define('RANDOM_STRING_TEXT', 0x01 );
43 if(! function_exists('random_string')) {
44 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
45 // generate a bit of entropy and run it through the whirlpool
46 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
47 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
48 return(substr($s,0,$size));
51 if(! function_exists('notags')) {
53 * This is our primary input filter.
55 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
56 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
57 * after cleansing, and angle chars with the high bit set could get through as markup.
59 * This is now disabled because it was interfering with some legitimate unicode sequences
60 * and hopefully there aren't a lot of those browsers left.
62 * Use this on any text input where angle chars are not valid or permitted
63 * They will be replaced with safer brackets. This may be filtered further
64 * if these are not allowed either.
66 * @param string $string Input string
67 * @return string Filtered string
69 function notags($string) {
71 return(str_replace(array("<",">"), array('[',']'), $string));
73 // High-bit filter no longer used
74 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
79 if(! function_exists('escape_tags')) {
81 * use this on "body" or "content" input where angle chars shouldn't be removed,
82 * and allow them to be safely displayed.
83 * @param string $string
86 function escape_tags($string) {
88 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
92 // generate a string that's random, but usually pronounceable.
93 // used to generate initial passwords
95 if(! function_exists('autoname')) {
97 * generate a string that's random, but usually pronounceable.
98 * used to generate initial passwords
102 function autoname($len) {
107 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
108 if(mt_rand(0,5) == 4)
126 's','sc','sh','sm','sp','st',
134 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
135 'nd','ng','nk','nt','rn','rp','rt');
137 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
138 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
140 $start = mt_rand(0,2);
148 for ($x = 0; $x < $len; $x ++) {
149 $r = mt_rand(0,count($table) - 1);
152 if($table == $vowels)
153 $table = array_merge($cons,$midcons);
159 $word = substr($word,0,$len);
161 foreach($noend as $noe) {
162 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
163 $word = substr($word,0,-1);
167 if(substr($word,-1) == 'q')
168 $word = substr($word,0,-1);
173 // escape text ($str) for XML transport
174 // returns escaped text.
176 if(! function_exists('xmlify')) {
178 * escape text ($str) for XML transport
180 * @return string Escaped text.
182 function xmlify($str) {
185 $len = mb_strlen($str);
186 for($x = 0; $x < $len; $x ++) {
187 $char = mb_substr($str,$x,1);
217 $buffer = mb_ereg_replace("&", "&", $str);
218 $buffer = mb_ereg_replace("'", "'", $buffer);
219 $buffer = mb_ereg_replace('"', """, $buffer);
220 $buffer = mb_ereg_replace("<", "<", $buffer);
221 $buffer = mb_ereg_replace(">", ">", $buffer);
223 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
224 $buffer = trim($buffer);
229 if(! function_exists('unxmlify')) {
232 * @param string $s xml escaped text
233 * @return string unescaped text
235 function unxmlify($s) {
236 // $ret = str_replace('&','&', $s);
237 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
238 /*$ret = mb_ereg_replace('&', '&', $s);
239 $ret = mb_ereg_replace(''', "'", $ret);
240 $ret = mb_ereg_replace('"', '"', $ret);
241 $ret = mb_ereg_replace('<', "<", $ret);
242 $ret = mb_ereg_replace('>', ">", $ret);
244 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
248 if(! function_exists('hex2bin')) {
250 * convenience wrapper, reverse the operation "bin2hex"
254 function hex2bin($s) {
255 if(! (is_string($s) && strlen($s)))
258 if(! ctype_xdigit($s)) {
262 return(pack("H*",$s));
266 if(! function_exists('paginate_data')) {
268 * Automatica pagination data.
270 * @param App $a App instance
271 * @param int $count [optional] item count (used with alt pager)
272 * @return Array data for pagination template
274 function paginate_data(&$a, $count=null) {
275 $stripped = preg_replace('/([&?]page=[0-9]*)/','',$a->query_string);
277 $stripped = str_replace('q=','',$stripped);
278 $stripped = trim($stripped,'/');
279 $pagenum = $a->pager['page'];
281 if (($a->page_offset != "") AND !preg_match('/[?&].offset=/', $stripped))
282 $stripped .= "&offset=".urlencode($a->page_offset);
284 $url = $a->get_baseurl() . '/' . $stripped;
287 function _l(&$d, $name, $url, $text, $class="") {
288 if (!strpos($url, "?")) {
289 if ($pos = strpos($url, "&"))
290 $url = substr($url, 0, $pos)."?".substr($url, $pos + 1);
293 $d[$name] = array('url'=>$url, 'text'=>$text, 'class'=>$class);
296 if (!is_null($count)){
298 if($a->pager['page']>1)
299 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('newer'));
301 _l($data, "next", $url.'&page='.($a->pager['page'] + 1), t('older'));
304 if($a->pager['total'] > $a->pager['itemspage']) {
305 if($a->pager['page'] != 1)
306 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('prev'));
308 _l($data, "first", $url."&page=1", t('first'));
311 $numpages = $a->pager['total'] / $a->pager['itemspage'];
314 $numstop = $numpages;
317 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
318 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
323 for($i = $numstart; $i <= $numstop; $i++){
324 if($i == $a->pager['page'])
325 _l($pages, $i, "#", $i, "current");
327 _l($pages, $i, $url."&page=$i", $i, "n");
330 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
331 if($i == $a->pager['page'])
332 _l($pages, $i, "#", $i, "current");
334 _l($pages, $i, $url."&page=$i", $i, "n");
337 $data['pages'] = $pages;
339 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
340 _l($data, "last", $url."&page=$lastpage", t('last'));
342 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
343 _l($data, "next", $url."&page=".($a->pager['page'] + 1), t('next'));
351 if(! function_exists('paginate')) {
353 * Automatic pagination.
355 * To use, get the count of total items.
356 * Then call $a->set_pager_total($number_items);
357 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
358 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
359 * (assuming there are enough items to paginate).
360 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
361 * will limit the results to the correct items for the current page.
362 * The actual page handling is then accomplished at the application layer.
364 * @param App $a App instance
365 * @return string html for pagination #FIXME remove html
367 function paginate(&$a) {
369 $data = paginate_data($a);
370 $tpl = get_markup_template("paginate.tpl");
371 return replace_macros($tpl, array("pager" => $data));
375 if(! function_exists('alt_pager')) {
378 * @param App $a App instance
380 * @return string html for pagination #FIXME remove html
382 function alt_pager(&$a, $i) {
384 $data = paginate_data($a, $i);
385 $tpl = get_markup_template("paginate.tpl");
386 return replace_macros($tpl, array('pager' => $data));
390 if(! function_exists('scroll_loader')) {
392 * Loader for infinite scrolling
393 * @return string html for loader
395 function scroll_loader() {
396 $tpl = get_markup_template("scroll_loader.tpl");
397 return replace_macros($tpl, array(
398 'wait' => t('Loading more entries...'),
399 'end' => t('The end')
403 if(! function_exists('expand_acl')) {
405 * Turn user/group ACLs stored as angle bracketed text into arrays
410 function expand_acl($s) {
411 // turn string array of angle-bracketed elements into numeric array
412 // e.g. "<1><2><3>" => array(1,2,3);
416 $t = str_replace('<','',$s);
417 $a = explode('>',$t);
420 $ret[] = intval($aa);
426 if(! function_exists('sanitise_acl')) {
428 * Wrap ACL elements in angle brackets for storage
429 * @param string $item
431 function sanitise_acl(&$item) {
433 $item = '<' . intval(notags(trim($item))) . '>';
439 if(! function_exists('perms2str')) {
441 * Convert an ACL array to a storable string
443 * Normally ACL permissions will be an array.
444 * We'll also allow a comma-separated string.
446 * @param string|array $p
449 function perms2str($p) {
454 $tmp = explode(',',$p);
457 array_walk($tmp,'sanitise_acl');
458 $ret = implode('',$tmp);
464 if(! function_exists('item_new_uri')) {
466 * generate a guaranteed unique (for this domain) item ID for ATOM
467 * safe from birthday paradox
469 * @param string $hostname
473 function item_new_uri($hostname,$uid, $guid = "") {
479 $hash = get_guid(32);
485 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
487 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
491 } while($dups == true);
495 // Generate a guaranteed unique photo ID.
496 // safe from birthday paradox
498 if(! function_exists('photo_new_resource')) {
500 * Generate a guaranteed unique photo ID.
501 * safe from birthday paradox
505 function photo_new_resource() {
509 $resource = hash('md5',uniqid(mt_rand(),true));
510 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
515 } while($found == true);
520 if(! function_exists('load_view_file')) {
523 * wrapper to load a view template, checking for alternate
524 * languages before falling back to the default
526 * @global string $lang
528 * @param string $s view name
531 function load_view_file($s) {
537 if(file_exists("$d/$lang/$b")) {
538 $stamp1 = microtime(true);
539 $content = file_get_contents("$d/$lang/$b");
540 $a->save_timestamp($stamp1, "file");
544 $theme = current_theme();
546 if(file_exists("$d/theme/$theme/$b")) {
547 $stamp1 = microtime(true);
548 $content = file_get_contents("$d/theme/$theme/$b");
549 $a->save_timestamp($stamp1, "file");
553 $stamp1 = microtime(true);
554 $content = file_get_contents($s);
555 $a->save_timestamp($stamp1, "file");
559 if(! function_exists('get_intltext_template')) {
561 * load a view template, checking for alternate
562 * languages before falling back to the default
564 * @global string $lang
565 * @param string $s view path
568 function get_intltext_template($s) {
573 if($a->theme['template_engine'] === 'smarty3')
574 $engine = "/smarty3";
579 if(file_exists("view/$lang$engine/$s")) {
580 $stamp1 = microtime(true);
581 $content = file_get_contents("view/$lang$engine/$s");
582 $a->save_timestamp($stamp1, "file");
584 } elseif(file_exists("view/en$engine/$s")) {
585 $stamp1 = microtime(true);
586 $content = file_get_contents("view/en$engine/$s");
587 $a->save_timestamp($stamp1, "file");
590 $stamp1 = microtime(true);
591 $content = file_get_contents("view$engine/$s");
592 $a->save_timestamp($stamp1, "file");
597 if(! function_exists('get_markup_template')) {
602 * @param string $root
605 function get_markup_template($s, $root = '') {
606 $stamp1 = microtime(true);
609 $t = $a->template_engine();
611 $template = $t->get_template_file($s, $root);
612 } catch (Exception $e) {
613 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
616 $a->save_timestamp($stamp1, "file");
621 if(! function_exists("get_template_file")) {
625 * @param string $filename
626 * @param string $root
629 function get_template_file($a, $filename, $root = '') {
630 $theme = current_theme();
632 // Make sure $root ends with a slash /
633 if($root !== '' && $root[strlen($root)-1] !== '/')
636 if(file_exists("{$root}view/theme/$theme/$filename"))
637 $template_file = "{$root}view/theme/$theme/$filename";
638 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
639 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
640 elseif (file_exists("{$root}/$filename"))
641 $template_file = "{$root}/$filename";
643 $template_file = "{$root}view/$filename";
645 return $template_file;
654 if(! function_exists('attribute_contains')) {
656 * for html,xml parsing - let's say you've got
657 * an attribute foobar="class1 class2 class3"
658 * and you want to find out if it contains 'class3'.
659 * you can't use a normal sub string search because you
660 * might match 'notclass3' and a regex to do the job is
661 * possible but a bit complicated.
662 * pass the attribute string as $attr and the attribute you
663 * are looking for as $s - returns true if found, otherwise false
665 * @param string $attr attribute value
666 * @param string $s string to search
667 * @return boolean True if found, False otherwise
669 function attribute_contains($attr,$s) {
670 $a = explode(' ', $attr);
671 if(count($a) && in_array($s,$a))
676 if(! function_exists('logger')) {
677 /* setup int->string log level map */
678 $LOGGER_LEVELS = array();
682 * LOGGER_NORMAL (default)
693 function logger($msg,$level = 0) {
694 // turn off logger in install mode
697 global $LOGGER_LEVELS;
699 if(($a->module == 'install') || (! ($db && $db->connected))) return;
701 if (count($LOGGER_LEVELS)==0){
702 foreach (get_defined_constants() as $k=>$v){
703 if (substr($k,0,7)=="LOGGER_")
704 $LOGGER_LEVELS[$v] = substr($k,7,7);
708 $debugging = get_config('system','debugging');
709 $loglevel = intval(get_config('system','loglevel'));
710 $logfile = get_config('system','logfile');
712 if((! $debugging) || (! $logfile) || ($level > $loglevel))
715 $callers = debug_backtrace();
716 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
719 $LOGGER_LEVELS[$level],
720 basename($callers[0]['file']),
722 $callers[1]['function'],
726 $stamp1 = microtime(true);
727 @file_put_contents($logfile, $logline, FILE_APPEND);
728 $a->save_timestamp($stamp1, "file");
733 if(! function_exists('activity_match')) {
735 * Compare activity uri. Knows about activity namespace.
737 * @param string $haystack
738 * @param string $needle
741 function activity_match($haystack,$needle) {
742 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
748 if(! function_exists('get_tags')) {
750 * Pull out all #hashtags and @person tags from $s;
751 * We also get @person@domain.com - which would make
752 * the regex quite complicated as tags can also
753 * end a sentence. So we'll run through our results
754 * and strip the period from any tags which end with one.
755 * Returns array of tags found, or empty array.
760 function get_tags($s) {
763 // Convert hashtag links to hashtags
764 $s = preg_replace("/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism", "#$2", $s);
766 // ignore anything in a code block
767 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
769 // Force line feeds at bbtags
770 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
772 // ignore anything in a bbtag
773 $s = preg_replace('/\[(.*?)\]/sm','',$s);
775 // Match full names against @tags including the space between first and last
776 // We will look these up afterward to see if they are full names or not recognisable.
778 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
779 foreach($match[1] as $mtch) {
780 if(strstr($mtch,"]")) {
781 // we might be inside a bbcode color tag - leave it alone
784 if(substr($mtch,-1,1) === '.')
785 $ret[] = substr($mtch,0,-1);
791 // Otherwise pull out single word tags. These can be @nickname, @first_last
794 if(preg_match_all('/([!#@][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
795 foreach($match[1] as $mtch) {
796 if(strstr($mtch,"]")) {
797 // we might be inside a bbcode color tag - leave it alone
800 if(substr($mtch,-1,1) === '.')
801 $mtch = substr($mtch,0,-1);
802 // ignore strictly numeric tags like #1
803 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
805 // try not to catch url fragments
806 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
817 if(! function_exists('qp')) {
819 * quick and dirty quoted_printable encoding
825 return str_replace ("%","=",rawurlencode($s));
830 if(! function_exists('get_mentions')) {
833 * @return string html for mentions #FIXME: remove html
835 function get_mentions($item) {
837 if(! strlen($item['tag']))
840 $arr = explode(',',$item['tag']);
841 foreach($arr as $x) {
843 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
844 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
845 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
849 if (!$item['private']) {
850 $o .= "\t\t".'<link rel="ostatus:attention" href="http://activityschema.org/collection/public"/>'."\r\n";
851 $o .= "\t\t".'<link rel="mentioned" href="http://activityschema.org/collection/public"/>'."\r\n";
857 if(! function_exists('contact_block')) {
859 * Get html for contact block.
861 * @template contact_block.tpl
862 * @hook contact_block_end (contacts=>array, output=>string)
865 function contact_block() {
869 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
875 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
877 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
878 WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0
879 AND `hidden` = 0 AND `archive` = 0
880 AND `network` IN ('%s', '%s', '%s')",
881 intval($a->profile['uid']),
883 dbesc(NETWORK_OSTATUS),
884 dbesc(NETWORK_DIASPORA)
887 $total = intval($r[0]['total']);
890 $contacts = t('No contacts');
894 $r = q("SELECT * FROM `contact`
895 WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0
896 AND `hidden` = 0 AND `archive` = 0
897 AND `network` IN ('%s', '%s', '%s') ORDER BY RAND() LIMIT %d",
898 intval($a->profile['uid']),
900 dbesc(NETWORK_OSTATUS),
901 dbesc(NETWORK_DIASPORA),
905 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
908 $micropro[] = micropro($rr,true,'mpfriend');
913 $tpl = get_markup_template('contact_block.tpl');
914 $o = replace_macros($tpl, array(
915 '$contacts' => $contacts,
916 '$nickname' => $a->profile['nickname'],
917 '$viewcontacts' => t('View Contacts'),
918 '$micropro' => $micropro,
921 $arr = array('contacts' => $r, 'output' => $o);
923 call_hooks('contact_block_end', $arr);
928 if(! function_exists('micropro')) {
931 * @param array $contact
932 * @param boolean $redirect
933 * @param string $class
934 * @param boolean $textmode
935 * @return string #FIXME: remove html
937 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
940 $class = ' ' . $class;
942 $url = $contact['url'];
948 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
949 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === NETWORK_DFRN)) {
951 $url = $redirect_url;
952 $sparkle = ' sparkle';
957 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
961 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
962 . (($click) ? ' fakelink' : '') . '" '
963 . (($redir) ? ' target="redir" ' : '')
964 . (($url) ? ' href="' . $url . '"' : '') . $click
965 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
966 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
969 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
970 . (($click) ? ' fakelink' : '') . '" '
971 . (($redir) ? ' target="redir" ' : '')
972 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
973 . proxy_url($contact['micro']) . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
974 . '" /></a></div>' . "\r\n";
980 if(! function_exists('search')) {
984 * @param string $s search query
985 * @param string $id html id
986 * @param string $url search url
987 * @param boolean $savedsearch show save search button
989 function search($s,$id='search-box',$url='/search',$save = false, $aside = true) {
995 '$action_url' => $a->get_baseurl((stristr($url,'network')) ? true : false) . $url,
996 '$search_label' => t('Search'),
997 '$save_label' => t('Save'),
998 '$savedsearch' => feature_enabled(local_user(),'savedsearch'),
1002 $values['$searchoption'] = array(
1008 return replace_macros(get_markup_template('searchbox.tpl'), $values);
1011 if(! function_exists('valid_email')) {
1013 * Check if $x is a valid email string
1018 function valid_email($x){
1020 if(get_config('system','disable_email_validation'))
1023 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
1029 if(! function_exists('linkify')) {
1031 * Replace naked text hyperlink with HTML formatted hyperlink
1035 function linkify($s) {
1036 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
1037 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
1045 * @return array index is present tense verb
1046 value is array containing past tense verb, translation of present, translation of past
1047 * @hook poke_verbs pokes array
1049 function get_poke_verbs() {
1051 // index is present tense verb
1052 // value is array containing past tense verb, translation of present, translation of past
1055 'poke' => array( 'poked', t('poke'), t('poked')),
1056 'ping' => array( 'pinged', t('ping'), t('pinged')),
1057 'prod' => array( 'prodded', t('prod'), t('prodded')),
1058 'slap' => array( 'slapped', t('slap'), t('slapped')),
1059 'finger' => array( 'fingered', t('finger'), t('fingered')),
1060 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1062 call_hooks('poke_verbs', $arr);
1068 * @return array index is mood, value is translated mood
1069 * @hook mood_verbs moods array
1071 function get_mood_verbs() {
1074 'happy' => t('happy'),
1076 'mellow' => t('mellow'),
1077 'tired' => t('tired'),
1078 'perky' => t('perky'),
1079 'angry' => t('angry'),
1080 'stupefied' => t('stupified'),
1081 'puzzled' => t('puzzled'),
1082 'interested' => t('interested'),
1083 'bitter' => t('bitter'),
1084 'cheerful' => t('cheerful'),
1085 'alive' => t('alive'),
1086 'annoyed' => t('annoyed'),
1087 'anxious' => t('anxious'),
1088 'cranky' => t('cranky'),
1089 'disturbed' => t('disturbed'),
1090 'frustrated' => t('frustrated'),
1091 'motivated' => t('motivated'),
1092 'relaxed' => t('relaxed'),
1093 'surprised' => t('surprised'),
1096 call_hooks('mood_verbs', $arr);
1102 if(! function_exists('smilies')) {
1104 * Replaces text emoticons with graphical images
1106 * It is expected that this function will be called using HTML text.
1107 * We will escape text between HTML pre and code blocks from being
1110 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
1111 * function from being executed by the prepare_text() routine when preparing
1112 * bbcode source for HTML display
1115 * @param boolean $sample
1117 * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1119 function smilies($s, $sample = false) {
1122 if(intval(get_config('system','no_smilies'))
1123 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1126 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1127 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1169 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1170 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1171 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1172 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1173 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1174 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1175 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1176 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1177 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1178 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1179 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1180 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1181 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1182 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1183 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1184 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
1185 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
1186 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
1187 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
1188 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
1189 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1190 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1191 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1192 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1193 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1194 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1195 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1196 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1197 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1198 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1199 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1200 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1201 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
1202 '<a href="http://redmatrix.me/">red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="red" />matrix</a>',
1203 '<a href="http://redmatrix.me/">red<img class="smiley" src="' . $a->get_baseurl() . '/images/rm-16.png" alt="red" />matrix</a>'
1206 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1207 call_hooks('smilie', $params);
1210 $s = '<div class="smiley-sample">';
1211 for($x = 0; $x < count($params['texts']); $x ++) {
1212 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1216 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
1217 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1220 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1221 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1227 function smile_encode($m) {
1228 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1231 function smile_decode($m) {
1232 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1237 * expand <3333 to the correct number of hearts
1242 function preg_heart($x) {
1244 if(strlen($x[1]) == 1)
1247 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1248 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1249 $r = str_replace($x[0],$t,$x[0]);
1254 if(! function_exists('day_translate')) {
1256 * Translate days and months names
1261 function day_translate($s) {
1262 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1263 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1266 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1267 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')),
1274 if(! function_exists('normalise_link')) {
1278 * @param string $url
1281 function normalise_link($url) {
1282 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1283 return(rtrim($ret,'/'));
1288 if(! function_exists('link_compare')) {
1290 * Compare two URLs to see if they are the same, but ignore
1291 * slight but hopefully insignificant differences such as if one
1292 * is https and the other isn't, or if one is www.something and
1293 * the other isn't - and also ignore case differences.
1295 * @param string $a first url
1296 * @param string $b second url
1297 * @return boolean True if the URLs match, otherwise False
1300 function link_compare($a,$b) {
1301 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1307 if(! function_exists('redir_private_images')) {
1309 * Find any non-embedded images in private items and add redir links to them
1312 * @param array $item
1314 function redir_private_images($a, &$item) {
1317 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1319 //logger("redir_private_images: matches = " . print_r($matches, true));
1320 foreach($matches as $mtch) {
1321 if(strpos($mtch[1], '/redir') !== false)
1324 if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1325 //logger("redir_private_images: redir");
1326 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1327 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1334 function put_item_in_cache(&$item, $update = false) {
1336 if (($item["rendered-hash"] != hash("md5", $item["body"])) OR ($item["rendered-hash"] == "") OR
1337 ($item["rendered-html"] == "") OR get_config("system", "ignore_cache")) {
1339 // The function "redir_private_images" changes the body.
1340 // I'm not sure if we should store it permanently, so we save the old value.
1341 $body = $item["body"];
1344 redir_private_images($a, $item);
1346 $item["rendered-html"] = prepare_text($item["body"]);
1347 $item["rendered-hash"] = hash("md5", $item["body"]);
1348 $item["body"] = $body;
1350 if ($update AND ($item["id"] != 0)) {
1351 q("UPDATE `item` SET `rendered-html` = '%s', `rendered-hash` = '%s' WHERE `id` = %d",
1352 dbesc($item["rendered-html"]), dbesc($item["rendered-hash"]), intval($item["id"]));
1357 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1358 // If attach is true, also add icons for item attachments
1360 if(! function_exists('prepare_body')) {
1362 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1363 * If attach is true, also add icons for item attachments
1365 * @param array $item
1366 * @param boolean $attach
1367 * @return string item body html
1368 * @hook prepare_body_init item array before any work
1369 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1370 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1372 function prepare_body(&$item,$attach = false, $preview = false) {
1375 call_hooks('prepare_body_init', $item);
1377 $searchpath = $a->get_baseurl()."/search?tag=";
1380 $hashtags = array();
1381 $mentions = array();
1383 if (!get_config('system','suppress_tags')) {
1384 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1385 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1387 foreach($taglist as $tag) {
1389 if ($tag["url"] == "")
1390 $tag["url"] = $searchpath.strtolower($tag["term"]);
1392 if ($tag["type"] == TERM_HASHTAG) {
1393 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1395 } elseif ($tag["type"] == TERM_MENTION) {
1396 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1399 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1403 $item['tags'] = $tags;
1404 $item['hashtags'] = $hashtags;
1405 $item['mentions'] = $mentions;
1407 put_item_in_cache($item, true);
1408 $s = $item["rendered-html"];
1410 require_once("mod/proxy.php");
1411 $s = proxy_parse_html($s);
1413 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1414 call_hooks('prepare_body', $prep_arr);
1415 $s = $prep_arr['html'];
1418 // Replace the blockquotes with quotes that are used in mails
1419 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1420 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1426 $arr = explode('[/attach],',$item['attach']);
1428 $as .= '<div class="body-attach">';
1429 foreach($arr as $r) {
1432 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1434 foreach($matches as $mtch) {
1437 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1438 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1440 $the_url = $mtch[1];
1442 if(strpos($mime, 'video') !== false) {
1445 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1446 '$baseurl' => $a->get_baseurl(),
1448 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1449 '$baseurl' => $a->get_baseurl(),
1453 $id = end(explode('/', $the_url));
1454 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1457 'title' => t('View Video'),
1464 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1466 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1467 $filesubtype = str_replace('.', '-', $filesubtype);
1471 $filesubtype = 'unkn';
1474 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1475 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1481 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1484 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1488 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1489 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1491 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1495 $as .= '<div class="clear"></div></div>';
1500 if(strpos($s,'<div class="map">') !== false && $item['coord']) {
1501 $x = generate_map(trim($item['coord']));
1503 $s = preg_replace('/\<div class\=\"map\"\>/','$0' . $x,$s);
1509 $spoilersearch = '<blockquote class="spoiler">';
1511 // Remove line breaks before the spoiler
1512 while ((strpos($s, "\n".$spoilersearch) !== false))
1513 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1514 while ((strpos($s, "<br />".$spoilersearch) !== false))
1515 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1517 while ((strpos($s, $spoilersearch) !== false)) {
1519 $pos = strpos($s, $spoilersearch);
1520 $rnd = random_string(8);
1521 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1522 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1523 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1526 // Look for quote with author
1527 $authorsearch = '<blockquote class="author">';
1529 while ((strpos($s, $authorsearch) !== false)) {
1531 $pos = strpos($s, $authorsearch);
1532 $rnd = random_string(8);
1533 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1534 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1535 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1538 // replace friendica image url size with theme preference
1539 if (x($a->theme_info,'item_image_size')){
1540 $ps = $a->theme_info['item_image_size'];
1542 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
1545 $prep_arr = array('item' => $item, 'html' => $s);
1546 call_hooks('prepare_body_final', $prep_arr);
1548 return $prep_arr['html'];
1552 if(! function_exists('prepare_text')) {
1554 * Given a text string, convert from bbcode to html and add smilie icons.
1556 * @param string $text
1559 function prepare_text($text) {
1561 require_once('include/bbcode.php');
1563 if(stristr($text,'[nosmile]'))
1566 $s = smilies(bbcode($text));
1574 * return array with details for categories and folders for an item
1576 * @param array $item
1580 * [ // categories array
1582 * 'name': 'category name',
1583 * 'removeurl': 'url to remove this category',
1584 * 'first': 'is the first in this array? true/false',
1585 * 'last': 'is the last in this array? true/false',
1591 * 'name': 'folder name',
1592 * 'removeurl': 'url to remove this folder',
1593 * 'first': 'is the first in this array? true/false',
1594 * 'last': 'is the last in this array? true/false',
1600 function get_cats_and_terms($item) {
1603 $categories = array();
1606 $matches = false; $first = true;
1607 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1609 foreach($matches as $mtch) {
1610 $categories[] = array(
1611 'name' => xmlify(file_tag_decode($mtch[1])),
1613 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1620 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1623 if(local_user() == $item['uid']) {
1624 $matches = false; $first = true;
1625 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1627 foreach($matches as $mtch) {
1629 'name' => xmlify(file_tag_decode($mtch[1])),
1631 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1640 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1642 return array($categories, $folders);
1647 if(! function_exists('feed_hublinks')) {
1649 * return atom link elements for all of our hubs
1650 * @return string hub link xml elements
1652 function feed_hublinks() {
1654 $hub = get_config('system','huburl');
1658 $hubs = explode(',', $hub);
1660 foreach($hubs as $h) {
1664 if ($h === '[internal]')
1665 $h = $a->get_baseurl() . '/pubsubhubbub';
1666 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1674 if(! function_exists('feed_salmonlinks')) {
1676 * return atom link elements for salmon endpoints
1677 * @param string $nick user nickname
1678 * @return string salmon link xml elements
1680 function feed_salmonlinks($nick) {
1684 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1686 // old style links that status.net still needed as of 12/2010
1688 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1689 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1693 if(! function_exists('get_plink')) {
1695 * get private link for item
1696 * @param array $item
1697 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1699 function get_plink($item) {
1702 if ($a->user['nickname'] != "") {
1704 //'href' => $a->get_baseurl()."/display/".$a->user['nickname']."/".$item['id'],
1705 'href' => $a->get_baseurl()."/display/".$item['guid'],
1706 'orig' => $a->get_baseurl()."/display/".$item['guid'],
1707 'title' => t('View on separate page'),
1708 'orig_title' => t('view on separate page'),
1711 if (x($item,'plink')) {
1712 $ret["href"] = $item['plink'];
1713 $ret["title"] = t('link to source');
1716 } elseif (x($item,'plink') && ($item['private'] != 1))
1718 'href' => $item['plink'],
1719 'orig' => $item['plink'],
1720 'title' => t('link to source'),
1725 //if (x($item,'plink') && ($item['private'] != 1))
1730 if(! function_exists('unamp')) {
1732 * replace html amp entity with amp char
1736 function unamp($s) {
1737 return str_replace('&', '&', $s);
1743 if(! function_exists('lang_selector')) {
1745 * get html for language selector
1746 * @global string $lang
1748 * @template lang_selector.tpl
1750 function lang_selector() {
1753 $langs = glob('view/*/strings.php');
1755 $lang_options = array();
1758 if(is_array($langs) && count($langs)) {
1760 if(! in_array('view/en/strings.php',$langs))
1761 $langs[] = 'view/en/';
1763 foreach($langs as $l) {
1765 $lang_options[""] = t('default');
1769 $ll = substr($ll,0,strrpos($ll,'/'));
1770 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1771 $lang_options[$ll]=$ll;
1775 $tpl = get_markup_template("lang_selector.tpl");
1776 $o = replace_macros($tpl, array(
1777 '$title' => t('Select an alternate language'),
1778 '$langs' => array($lang_options, $selected),
1785 if(! function_exists('return_bytes')) {
1787 * return number of bytes in size (K, M, G)
1788 * @param string $size_str
1791 function return_bytes ($size_str) {
1792 switch (substr ($size_str, -1))
1794 case 'M': case 'm': return (int)$size_str * 1048576;
1795 case 'K': case 'k': return (int)$size_str * 1024;
1796 case 'G': case 'g': return (int)$size_str * 1073741824;
1797 default: return $size_str;
1804 function generate_user_guid() {
1807 $guid = get_guid(32);
1808 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1813 } while ($found == true );
1820 * @param boolean $strip_padding
1823 function base64url_encode($s, $strip_padding = false) {
1825 $s = strtr(base64_encode($s),'+/','-_');
1828 $s = str_replace('=','',$s);
1837 function base64url_decode($s) {
1840 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1845 * // Placeholder for new rev of salmon which strips base64 padding.
1846 * // PHP base64_decode handles the un-padded input without requiring this step
1847 * // Uncomment if you find you need it.
1850 * if(! strpos($s,'=')) {
1860 return base64_decode(strtr($s,'-_','+/'));
1864 if (!function_exists('str_getcsv')) {
1868 * @param string $input
1869 * @param string $delimiter
1870 * @param string $enclosure
1871 * @param string $escape
1872 * @param string $eol
1873 * @return boolean|array False on error, otherwise array[row][column]
1875 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1876 if (is_string($input) && !empty($input)) {
1878 $tmp = preg_split("/".$eol."/",$input);
1879 if (is_array($tmp) && !empty($tmp)) {
1880 while (list($line_num, $line) = each($tmp)) {
1881 if (preg_match("/".$escape.$enclosure."/",$line)) {
1882 while ($strlen = strlen($line)) {
1883 $pos_delimiter = strpos($line,$delimiter);
1884 $pos_enclosure_start = strpos($line,$enclosure);
1886 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1887 && ($pos_enclosure_start < $pos_delimiter)
1889 $enclosed_str = substr($line,1);
1890 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1891 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1892 $output[$line_num][] = $enclosed_str;
1893 $offset = $pos_enclosure_end+3;
1895 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1896 $output[$line_num][] = substr($line,0);
1897 $offset = strlen($line);
1899 $output[$line_num][] = substr($line,0,$pos_delimiter);
1901 !empty($pos_enclosure_start)
1902 && ($pos_enclosure_start < $pos_delimiter)
1904 ?$pos_enclosure_start
1908 $line = substr($line,$offset);
1911 $line = preg_split("/".$delimiter."/",$line);
1914 * Validating against pesky extra line breaks creating false rows.
1916 if (is_array($line) && !empty($line[0])) {
1917 $output[$line_num] = $line;
1932 * return div element with class 'clear'
1936 function cleardiv() {
1937 return '<div class="clear"></div>';
1941 function bb_translate_video($s) {
1944 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1946 foreach($matches as $mtch) {
1947 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1948 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1949 elseif(stristr($mtch[1],'vimeo'))
1950 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1956 function html2bb_video($s) {
1958 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1959 '[youtube]$2[/youtube]', $s);
1961 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1962 '[youtube]$2[/youtube]', $s);
1964 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1965 '[vimeo]$2[/vimeo]', $s);
1971 * apply xmlify() to all values of array $val, recursively
1975 function array_xmlify($val){
1976 if (is_bool($val)) return $val?"true":"false";
1977 if (is_array($val)) return array_map('array_xmlify', $val);
1978 return xmlify((string) $val);
1983 * transorm link href and img src from relative to absolute
1985 * @param string $text
1986 * @param string $base base url
1989 function reltoabs($text, $base)
1994 $base = rtrim($base,'/');
1996 $base2 = $base . "/";
1999 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
2000 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
2001 $text = preg_replace($pattern, $replace, $text);
2003 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
2004 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
2005 $text = preg_replace($pattern, $replace, $text);
2008 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
2009 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
2010 $text = preg_replace($pattern, $replace, $text);
2012 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
2013 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
2014 $text = preg_replace($pattern, $replace, $text);
2022 * get translated item type
2024 * @param array $itme
2027 function item_post_type($item) {
2028 if(intval($item['event-id']))
2030 if(strlen($item['resource-id']))
2032 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
2033 return t('activity');
2034 if($item['id'] != $item['parent'])
2035 return t('comment');
2039 // post categories and "save to file" use the same item.file table for storage.
2040 // We will differentiate the different uses by wrapping categories in angle brackets
2041 // and save to file categories in square brackets.
2042 // To do this we need to escape these characters if they appear in our tag.
2044 function file_tag_encode($s) {
2045 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
2048 function file_tag_decode($s) {
2049 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
2052 function file_tag_file_query($table,$s,$type = 'file') {
2055 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
2057 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
2058 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
2061 // ex. given music,video return <music><video> or [music][video]
2062 function file_tag_list_to_file($list,$type = 'file') {
2065 $list_array = explode(",",$list);
2066 if($type == 'file') {
2075 foreach($list_array as $item) {
2077 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
2084 // ex. given <music><video>[friends], return music,video or friends
2085 function file_tag_file_to_list($file,$type = 'file') {
2088 if($type == 'file') {
2089 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
2092 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
2095 foreach($matches as $mtch) {
2098 $list .= file_tag_decode($mtch[1]);
2105 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
2106 // $file_old - categories previously associated with an item
2107 // $file_new - new list of categories for an item
2112 if($file_old == $file_new)
2115 $saved = get_pconfig($uid,'system','filetags');
2116 if(strlen($saved)) {
2117 if($type == 'file') {
2120 $termtype = TERM_FILE;
2125 $termtype = TERM_CATEGORY;
2128 $filetags_updated = $saved;
2130 // check for new tags to be added as filetags in pconfig
2131 $new_tags = array();
2132 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2134 foreach($check_new_tags as $tag) {
2135 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2139 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2141 // check for deleted tags to be removed from filetags in pconfig
2142 $deleted_tags = array();
2143 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2145 foreach($check_deleted_tags as $tag) {
2146 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2147 $deleted_tags[] = $tag;
2150 foreach($deleted_tags as $key => $tag) {
2151 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2153 intval(TERM_OBJ_POST),
2157 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2162 unset($deleted_tags[$key]);
2165 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2169 if($saved != $filetags_updated) {
2170 set_pconfig($uid,'system','filetags', $filetags_updated);
2175 if(strlen($file_new)) {
2176 set_pconfig($uid,'system','filetags', $file_new);
2181 function file_tag_save_file($uid,$item,$file) {
2182 require_once("include/files.php");
2187 $r = q("select file from item where id = %d and uid = %d limit 1",
2192 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2193 q("update item set file = '%s' where id = %d and uid = %d",
2194 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2199 create_files_from_item($item);
2201 $saved = get_pconfig($uid,'system','filetags');
2202 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2203 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2204 info( t('Item filed') );
2209 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2210 require_once("include/files.php");
2217 $pattern = '<' . file_tag_encode($file) . '>' ;
2218 $termtype = TERM_CATEGORY;
2220 $pattern = '[' . file_tag_encode($file) . ']' ;
2221 $termtype = TERM_FILE;
2225 $r = q("select file from item where id = %d and uid = %d limit 1",
2232 q("update item set file = '%s' where id = %d and uid = %d",
2233 dbesc(str_replace($pattern,'',$r[0]['file'])),
2238 create_files_from_item($item);
2240 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2242 intval(TERM_OBJ_POST),
2246 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2250 $saved = get_pconfig($uid,'system','filetags');
2251 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2257 function normalise_openid($s) {
2258 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2262 function undo_post_tagging($s) {
2264 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2266 foreach($matches as $mtch) {
2267 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2273 function fix_mce_lf($s) {
2274 $s = str_replace("\r\n","\n",$s);
2275 // $s = str_replace("\n\n","\n",$s);
2280 function protect_sprintf($s) {
2281 return(str_replace('%','%%',$s));
2285 function is_a_date_arg($s) {
2289 if($i <= $y+1 && strpos($s,'-') == 4) {
2290 $m = intval(substr($s,5));
2291 if($m > 0 && $m <= 12)
2299 * remove intentation from a text
2301 function deindent($text, $chr="[\t ]", $count=NULL) {
2302 $text = fix_mce_lf($text);
2303 $lines = explode("\n", $text);
2304 if (is_null($count)) {
2306 $k=0; while($k<count($lines) && strlen($lines[$k])==0) $k++;
2307 preg_match("|^".$chr."*|", $lines[$k], $m);
2308 $count = strlen($m[0]);
2310 for ($k=0; $k<count($lines); $k++){
2311 $lines[$k] = preg_replace("|^".$chr."{".$count."}|", "", $lines[$k]);
2314 return implode("\n", $lines);
2317 function formatBytes($bytes, $precision = 2) {
2318 $units = array('B', 'KB', 'MB', 'GB', 'TB');
2320 $bytes = max($bytes, 0);
2321 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
2322 $pow = min($pow, count($units) - 1);
2324 $bytes /= pow(1024, $pow);
2326 return round($bytes, $precision) . ' ' . $units[$pow];