3 // This is our template processor.
4 // $s is the string requiring macro substitution.
5 // $r is an array of key value pairs (search => replace)
6 // returns substituted string.
7 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
8 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
9 // depending on the order in which they were declared in the array.
11 require_once("include/template_processor.php");
12 require_once("include/friendica_smarty.php");
14 if(! function_exists('replace_macros')) {
16 * This is our template processor
18 * @param string|FriendicaSmarty $s the string requiring macro substitution,
19 * or an instance of FriendicaSmarty
20 * @param array $r key value pairs (search => replace)
21 * @return string substituted string
23 function replace_macros($s,$r) {
25 $stamp1 = microtime(true);
29 $t = $a->template_engine();
31 $output = $t->replace_macros($s,$r);
32 } catch (Exception $e) {
33 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
36 $a->save_timestamp($stamp1, "rendering");
42 // random string, there are 86 characters max in text mode, 128 for hex
45 define('RANDOM_STRING_HEX', 0x00 );
46 define('RANDOM_STRING_TEXT', 0x01 );
48 if(! function_exists('random_string')) {
49 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
50 // generate a bit of entropy and run it through the whirlpool
51 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
52 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
53 return(substr($s,0,$size));
56 if(! function_exists('notags')) {
58 * This is our primary input filter.
60 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
61 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
62 * after cleansing, and angle chars with the high bit set could get through as markup.
64 * This is now disabled because it was interfering with some legitimate unicode sequences
65 * and hopefully there aren't a lot of those browsers left.
67 * Use this on any text input where angle chars are not valid or permitted
68 * They will be replaced with safer brackets. This may be filtered further
69 * if these are not allowed either.
71 * @param string $string Input string
72 * @return string Filtered string
74 function notags($string) {
76 return(str_replace(array("<",">"), array('[',']'), $string));
78 // High-bit filter no longer used
79 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
84 if(! function_exists('escape_tags')) {
86 * use this on "body" or "content" input where angle chars shouldn't be removed,
87 * and allow them to be safely displayed.
88 * @param string $string
91 function escape_tags($string) {
93 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
97 // generate a string that's random, but usually pronounceable.
98 // used to generate initial passwords
100 if(! function_exists('autoname')) {
102 * generate a string that's random, but usually pronounceable.
103 * used to generate initial passwords
107 function autoname($len) {
112 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
113 if(mt_rand(0,5) == 4)
131 's','sc','sh','sm','sp','st',
139 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
140 'nd','ng','nk','nt','rn','rp','rt');
142 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
143 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
145 $start = mt_rand(0,2);
153 for ($x = 0; $x < $len; $x ++) {
154 $r = mt_rand(0,count($table) - 1);
157 if($table == $vowels)
158 $table = array_merge($cons,$midcons);
164 $word = substr($word,0,$len);
166 foreach($noend as $noe) {
167 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
168 $word = substr($word,0,-1);
172 if(substr($word,-1) == 'q')
173 $word = substr($word,0,-1);
178 // escape text ($str) for XML transport
179 // returns escaped text.
181 if(! function_exists('xmlify')) {
183 * escape text ($str) for XML transport
185 * @return string Escaped text.
187 function xmlify($str) {
190 $len = mb_strlen($str);
191 for($x = 0; $x < $len; $x ++) {
192 $char = mb_substr($str,$x,1);
222 $buffer = mb_ereg_replace("&", "&", $str);
223 $buffer = mb_ereg_replace("'", "'", $buffer);
224 $buffer = mb_ereg_replace('"', """, $buffer);
225 $buffer = mb_ereg_replace("<", "<", $buffer);
226 $buffer = mb_ereg_replace(">", ">", $buffer);
228 $buffer = htmlspecialchars($str, ENT_QUOTES);
229 $buffer = trim($buffer);
234 if(! function_exists('unxmlify')) {
237 * @param string $s xml escaped text
238 * @return string unescaped text
240 function unxmlify($s) {
241 // $ret = str_replace('&','&', $s);
242 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
243 /*$ret = mb_ereg_replace('&', '&', $s);
244 $ret = mb_ereg_replace(''', "'", $ret);
245 $ret = mb_ereg_replace('"', '"', $ret);
246 $ret = mb_ereg_replace('<', "<", $ret);
247 $ret = mb_ereg_replace('>', ">", $ret);
249 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
253 if(! function_exists('hex2bin')) {
255 * convenience wrapper, reverse the operation "bin2hex"
259 function hex2bin($s) {
260 if(! (is_string($s) && strlen($s)))
263 if(! ctype_xdigit($s)) {
267 return(pack("H*",$s));
271 if(! function_exists('paginate_data')) {
273 * Automatica pagination data.
275 * @param App $a App instance
276 * @param int $count [optional] item count (used with alt pager)
277 * @return Array data for pagination template
279 function paginate_data(&$a, $count=null) {
280 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
282 $stripped = str_replace('q=','',$stripped);
283 $stripped = trim($stripped,'/');
284 $pagenum = $a->pager['page'];
286 if (($a->page_offset != "") AND !strstr($stripped, "&offset="))
287 $stripped .= "&offset=".urlencode($a->page_offset);
288 if (!strpos($stripped, "?")) {
289 if ($pos = strpos($stripped, "&"))
290 $stripped = substr($stripped, 0, $pos)."?".substr($stripped, $pos + 1);
293 $url = $a->get_baseurl() . '/' . $stripped;
296 function _l(&$d, $name, $url, $text, $class="") {
298 $d[$name] = array('url'=>$url, 'text'=>$text, 'class'=>$class);
301 if (!is_null($count)){
303 if($a->pager['page']>1)
304 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('newer'));
306 _l($data, "next", $url.'&page='.($a->pager['page'] + 1), t('older'));
309 if($a->pager['total'] > $a->pager['itemspage']) {
310 if($a->pager['page'] != 1)
311 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('prev'));
313 _l($data, "first", $url."&page=1", t('first'));
316 $numpages = $a->pager['total'] / $a->pager['itemspage'];
319 $numstop = $numpages;
322 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
323 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
328 for($i = $numstart; $i <= $numstop; $i++){
329 if($i == $a->pager['page'])
330 _l($pages, $i, "#", $i, "current");
332 _l($pages, $i, $url."&page=$i", $i, "n");
335 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
336 if($i == $a->pager['page'])
337 _l($pages, $i, "#", $i, "current");
339 _l($pages, $i, $url."&page=$i", $i, "n");
342 $data['pages'] = $pages;
344 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
345 _l($data, "last", $url."&page=$lastpage", t('last'));
347 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
348 _l($data, "next", $url."&page=".($a->pager['page'] + 1), t('next'));
356 if(! function_exists('paginate')) {
358 * Automatic pagination.
360 * To use, get the count of total items.
361 * Then call $a->set_pager_total($number_items);
362 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
363 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
364 * (assuming there are enough items to paginate).
365 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
366 * will limit the results to the correct items for the current page.
367 * The actual page handling is then accomplished at the application layer.
369 * @param App $a App instance
370 * @return string html for pagination #FIXME remove html
372 function paginate(&$a) {
374 $data = paginate_data($a);
375 $tpl = get_markup_template("paginate.tpl");
376 return replace_macros($tpl, array("pager" => $data));
380 if(! function_exists('alt_pager')) {
383 * @param App $a App instance
385 * @return string html for pagination #FIXME remove html
387 function alt_pager(&$a, $i) {
389 $data = paginate_data($a, $i);
390 $tpl = get_markup_template("paginate.tpl");
391 return replace_macros($tpl, array('pager' => $data));
396 if(! function_exists('expand_acl')) {
398 * Turn user/group ACLs stored as angle bracketed text into arrays
403 function expand_acl($s) {
404 // turn string array of angle-bracketed elements into numeric array
405 // e.g. "<1><2><3>" => array(1,2,3);
409 $t = str_replace('<','',$s);
410 $a = explode('>',$t);
413 $ret[] = intval($aa);
419 if(! function_exists('sanitise_acl')) {
421 * Wrap ACL elements in angle brackets for storage
422 * @param string $item
424 function sanitise_acl(&$item) {
426 $item = '<' . intval(notags(trim($item))) . '>';
432 if(! function_exists('perms2str')) {
434 * Convert an ACL array to a storable string
436 * Normally ACL permissions will be an array.
437 * We'll also allow a comma-separated string.
439 * @param string|array $p
442 function perms2str($p) {
447 $tmp = explode(',',$p);
450 array_walk($tmp,'sanitise_acl');
451 $ret = implode('',$tmp);
457 if(! function_exists('item_new_uri')) {
459 * generate a guaranteed unique (for this domain) item ID for ATOM
460 * safe from birthday paradox
462 * @param string $hostname
466 function item_new_uri($hostname,$uid) {
470 $hash = random_string();
472 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
474 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
478 } while($dups == true);
482 // Generate a guaranteed unique photo ID.
483 // safe from birthday paradox
485 if(! function_exists('photo_new_resource')) {
487 * Generate a guaranteed unique photo ID.
488 * safe from birthday paradox
492 function photo_new_resource() {
496 $resource = hash('md5',uniqid(mt_rand(),true));
497 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
502 } while($found == true);
507 if(! function_exists('load_view_file')) {
510 * wrapper to load a view template, checking for alternate
511 * languages before falling back to the default
513 * @global string $lang
515 * @param string $s view name
518 function load_view_file($s) {
524 if(file_exists("$d/$lang/$b")) {
525 $stamp1 = microtime(true);
526 $content = file_get_contents("$d/$lang/$b");
527 $a->save_timestamp($stamp1, "file");
531 $theme = current_theme();
533 if(file_exists("$d/theme/$theme/$b")) {
534 $stamp1 = microtime(true);
535 $content = file_get_contents("$d/theme/$theme/$b");
536 $a->save_timestamp($stamp1, "file");
540 $stamp1 = microtime(true);
541 $content = file_get_contents($s);
542 $a->save_timestamp($stamp1, "file");
546 if(! function_exists('get_intltext_template')) {
548 * load a view template, checking for alternate
549 * languages before falling back to the default
551 * @global string $lang
552 * @param string $s view path
555 function get_intltext_template($s) {
560 if($a->theme['template_engine'] === 'smarty3')
561 $engine = "/smarty3";
566 if(file_exists("view/$lang$engine/$s")) {
567 $stamp1 = microtime(true);
568 $content = file_get_contents("view/$lang$engine/$s");
569 $a->save_timestamp($stamp1, "file");
571 } elseif(file_exists("view/en$engine/$s")) {
572 $stamp1 = microtime(true);
573 $content = file_get_contents("view/en$engine/$s");
574 $a->save_timestamp($stamp1, "file");
577 $stamp1 = microtime(true);
578 $content = file_get_contents("view$engine/$s");
579 $a->save_timestamp($stamp1, "file");
584 if(! function_exists('get_markup_template')) {
589 * @param string $root
592 function get_markup_template($s, $root = '') {
593 $stamp1 = microtime(true);
596 $t = $a->template_engine();
598 $template = $t->get_template_file($s, $root);
599 } catch (Exception $e) {
600 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
603 $a->save_timestamp($stamp1, "file");
608 if(! function_exists("get_template_file")) {
612 * @param string $filename
613 * @param string $root
616 function get_template_file($a, $filename, $root = '') {
617 $theme = current_theme();
619 // Make sure $root ends with a slash /
620 if($root !== '' && $root[strlen($root)-1] !== '/')
623 if(file_exists("{$root}view/theme/$theme/$filename"))
624 $template_file = "{$root}view/theme/$theme/$filename";
625 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
626 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
627 elseif (file_exists("{$root}/$filename"))
628 $template_file = "{$root}/$filename";
630 $template_file = "{$root}view/$filename";
632 return $template_file;
641 if(! function_exists('attribute_contains')) {
643 * for html,xml parsing - let's say you've got
644 * an attribute foobar="class1 class2 class3"
645 * and you want to find out if it contains 'class3'.
646 * you can't use a normal sub string search because you
647 * might match 'notclass3' and a regex to do the job is
648 * possible but a bit complicated.
649 * pass the attribute string as $attr and the attribute you
650 * are looking for as $s - returns true if found, otherwise false
652 * @param string $attr attribute value
653 * @param string $s string to search
654 * @return boolean True if found, False otherwise
656 function attribute_contains($attr,$s) {
657 $a = explode(' ', $attr);
658 if(count($a) && in_array($s,$a))
663 if(! function_exists('logger')) {
666 * LOGGER_NORMAL (default)
677 function logger($msg,$level = 0) {
678 // turn off logger in install mode
682 if(($a->module == 'install') || (! ($db && $db->connected))) return;
684 $debugging = get_config('system','debugging');
685 $loglevel = intval(get_config('system','loglevel'));
686 $logfile = get_config('system','logfile');
688 if((! $debugging) || (! $logfile) || ($level > $loglevel))
691 $stamp1 = microtime(true);
692 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
693 $a->save_timestamp($stamp1, "file");
698 if(! function_exists('activity_match')) {
700 * Compare activity uri. Knows about activity namespace.
702 * @param string $haystack
703 * @param string $needle
706 function activity_match($haystack,$needle) {
707 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
713 if(! function_exists('get_tags')) {
715 * Pull out all #hashtags and @person tags from $s;
716 * We also get @person@domain.com - which would make
717 * the regex quite complicated as tags can also
718 * end a sentence. So we'll run through our results
719 * and strip the period from any tags which end with one.
720 * Returns array of tags found, or empty array.
725 function get_tags($s) {
728 // ignore anything in a code block
729 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
731 // Force line feeds at bbtags
732 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
734 // ignore anything in a bbtag
735 $s = preg_replace('/\[(.*?)\]/sm','',$s);
737 // Match full names against @tags including the space between first and last
738 // We will look these up afterward to see if they are full names or not recognisable.
740 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
741 foreach($match[1] as $mtch) {
742 if(strstr($mtch,"]")) {
743 // we might be inside a bbcode color tag - leave it alone
746 if(substr($mtch,-1,1) === '.')
747 $ret[] = substr($mtch,0,-1);
753 // Otherwise pull out single word tags. These can be @nickname, @first_last
756 if(preg_match_all('/([!#@][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
757 foreach($match[1] as $mtch) {
758 if(strstr($mtch,"]")) {
759 // we might be inside a bbcode color tag - leave it alone
762 if(substr($mtch,-1,1) === '.')
763 $mtch = substr($mtch,0,-1);
764 // ignore strictly numeric tags like #1
765 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
767 // try not to catch url fragments
768 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
779 if(! function_exists('qp')) {
781 * quick and dirty quoted_printable encoding
787 return str_replace ("%","=",rawurlencode($s));
792 if(! function_exists('get_mentions')) {
795 * @return string html for mentions #FIXME: remove html
797 function get_mentions($item) {
799 if(! strlen($item['tag']))
802 $arr = explode(',',$item['tag']);
803 foreach($arr as $x) {
805 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
806 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
807 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
813 if(! function_exists('contact_block')) {
815 * Get html for contact block.
817 * @template contact_block.tpl
818 * @hook contact_block_end (contacts=>array, output=>string)
821 function contact_block() {
825 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
831 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
833 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0",
834 intval($a->profile['uid'])
837 $total = intval($r[0]['total']);
840 $contacts = t('No contacts');
844 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY RAND() LIMIT %d",
845 intval($a->profile['uid']),
849 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
852 $micropro[] = micropro($rr,true,'mpfriend');
857 $tpl = get_markup_template('contact_block.tpl');
858 $o = replace_macros($tpl, array(
859 '$contacts' => $contacts,
860 '$nickname' => $a->profile['nickname'],
861 '$viewcontacts' => t('View Contacts'),
862 '$micropro' => $micropro,
865 $arr = array('contacts' => $r, 'output' => $o);
867 call_hooks('contact_block_end', $arr);
872 if(! function_exists('micropro')) {
875 * @param array $contact
876 * @param boolean $redirect
877 * @param string $class
878 * @param boolean $textmode
879 * @return string #FIXME: remove html
881 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
884 $class = ' ' . $class;
886 $url = $contact['url'];
892 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
893 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
895 $url = $redirect_url;
896 $sparkle = ' sparkle';
901 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
905 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
906 . (($click) ? ' fakelink' : '') . '" '
907 . (($redir) ? ' target="redir" ' : '')
908 . (($url) ? ' href="' . $url . '"' : '') . $click
909 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
910 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
913 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
914 . (($click) ? ' fakelink' : '') . '" '
915 . (($redir) ? ' target="redir" ' : '')
916 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
917 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
918 . '" /></a></div>' . "\r\n";
924 if(! function_exists('search')) {
928 * @param string $s search query
929 * @param string $id html id
930 * @param string $url search url
931 * @param boolean $save show save search button
932 * @return string html for search box #FIXME: remove html
934 function search($s,$id='search-box',$url='/search',$save = false) {
936 $o = '<div id="' . $id . '">';
937 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
938 $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
939 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
941 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
942 $o .= '</form></div>';
946 if(! function_exists('valid_email')) {
948 * Check if $x is a valid email string
953 function valid_email($x){
955 if(get_config('system','disable_email_validation'))
958 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
964 if(! function_exists('linkify')) {
966 * Replace naked text hyperlink with HTML formatted hyperlink
970 function linkify($s) {
971 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
972 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
980 * @return array index is present tense verb
981 value is array containing past tense verb, translation of present, translation of past
982 * @hook poke_verbs pokes array
984 function get_poke_verbs() {
986 // index is present tense verb
987 // value is array containing past tense verb, translation of present, translation of past
990 'poke' => array( 'poked', t('poke'), t('poked')),
991 'ping' => array( 'pinged', t('ping'), t('pinged')),
992 'prod' => array( 'prodded', t('prod'), t('prodded')),
993 'slap' => array( 'slapped', t('slap'), t('slapped')),
994 'finger' => array( 'fingered', t('finger'), t('fingered')),
995 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
997 call_hooks('poke_verbs', $arr);
1003 * @return array index is mood, value is translated mood
1004 * @hook mood_verbs moods array
1006 function get_mood_verbs() {
1009 'happy' => t('happy'),
1011 'mellow' => t('mellow'),
1012 'tired' => t('tired'),
1013 'perky' => t('perky'),
1014 'angry' => t('angry'),
1015 'stupefied' => t('stupified'),
1016 'puzzled' => t('puzzled'),
1017 'interested' => t('interested'),
1018 'bitter' => t('bitter'),
1019 'cheerful' => t('cheerful'),
1020 'alive' => t('alive'),
1021 'annoyed' => t('annoyed'),
1022 'anxious' => t('anxious'),
1023 'cranky' => t('cranky'),
1024 'disturbed' => t('disturbed'),
1025 'frustrated' => t('frustrated'),
1026 'motivated' => t('motivated'),
1027 'relaxed' => t('relaxed'),
1028 'surprised' => t('surprised'),
1031 call_hooks('mood_verbs', $arr);
1037 if(! function_exists('smilies')) {
1039 * Replaces text emoticons with graphical images
1041 * It is expected that this function will be called using HTML text.
1042 * We will escape text between HTML pre and code blocks from being
1045 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
1046 * function from being executed by the prepare_text() routine when preparing
1047 * bbcode source for HTML display
1050 * @param boolean $sample
1052 * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1054 function smilies($s, $sample = false) {
1057 if(intval(get_config('system','no_smilies'))
1058 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1061 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1062 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1103 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1104 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1105 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1106 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1107 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1108 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1109 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1110 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1111 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1112 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1113 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1114 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1115 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1116 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1117 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1118 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
1119 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
1120 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
1121 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
1122 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
1123 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1124 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1125 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1126 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1127 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1128 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1129 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1130 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1131 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1132 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1133 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1134 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1135 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
1136 '<a href="http://redmatrix.me/">red <img class="smiley" src="' . $a->get_baseurl() . '/images/rhash-16.png" alt="red" /></a>'
1139 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1140 call_hooks('smilie', $params);
1143 $s = '<div class="smiley-sample">';
1144 for($x = 0; $x < count($params['texts']); $x ++) {
1145 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1149 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
1150 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1153 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1154 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1160 function smile_encode($m) {
1161 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1164 function smile_decode($m) {
1165 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1170 * expand <3333 to the correct number of hearts
1175 function preg_heart($x) {
1177 if(strlen($x[1]) == 1)
1180 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1181 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1182 $r = str_replace($x[0],$t,$x[0]);
1187 if(! function_exists('day_translate')) {
1189 * Translate days and months names
1194 function day_translate($s) {
1195 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1196 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1199 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1200 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')),
1207 if(! function_exists('normalise_link')) {
1211 * @param string $url
1214 function normalise_link($url) {
1215 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1216 return(rtrim($ret,'/'));
1221 if(! function_exists('link_compare')) {
1223 * Compare two URLs to see if they are the same, but ignore
1224 * slight but hopefully insignificant differences such as if one
1225 * is https and the other isn't, or if one is www.something and
1226 * the other isn't - and also ignore case differences.
1228 * @param string $a first url
1229 * @param string $b second url
1230 * @return boolean True if the URLs match, otherwise False
1233 function link_compare($a,$b) {
1234 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1240 if(! function_exists('redir_private_images')) {
1242 * Find any non-embedded images in private items and add redir links to them
1245 * @param array $item
1247 function redir_private_images($a, &$item) {
1250 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1252 //logger("redir_private_images: matches = " . print_r($matches, true));
1253 foreach($matches as $mtch) {
1254 if(strpos($mtch[1], '/redir') !== false)
1257 if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1258 //logger("redir_private_images: redir");
1259 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1260 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1268 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1269 // If attach is true, also add icons for item attachments
1271 if(! function_exists('prepare_body')) {
1273 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1274 * If attach is true, also add icons for item attachments
1276 * @param array $item
1277 * @param boolean $attach
1278 * @return string item body html
1279 * @hook prepare_body_init item array before any work
1280 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1281 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1283 function prepare_body(&$item,$attach = false) {
1286 call_hooks('prepare_body_init', $item);
1288 $searchpath = $a->get_baseurl()."/search?tag=";
1291 $hashtags = array();
1292 $mentions = array();
1294 if (!get_config('system','suppress_tags')) {
1295 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1296 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1298 foreach($taglist as $tag) {
1300 if ($tag["url"] == "")
1301 $tag["url"] = $searchpath.strtolower($tag["term"]);
1303 if ($tag["type"] == TERM_HASHTAG) {
1304 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1306 } elseif ($tag["type"] == TERM_MENTION) {
1307 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1310 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1314 $item['tags'] = $tags;
1315 $item['hashtags'] = $hashtags;
1316 $item['mentions'] = $mentions;
1319 //$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
1320 $cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
1322 if (($cachefile != '')) {
1323 if (file_exists($cachefile)) {
1324 $stamp1 = microtime(true);
1325 $s = file_get_contents($cachefile);
1326 $a->save_timestamp($stamp1, "file");
1328 redir_private_images($a, $item);
1329 $s = prepare_text($item['body']);
1331 $stamp1 = microtime(true);
1332 file_put_contents($cachefile, $s);
1333 $a->save_timestamp($stamp1, "file");
1335 logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
1338 redir_private_images($a, $item);
1339 $s = prepare_text($item['body']);
1343 $prep_arr = array('item' => $item, 'html' => $s);
1344 call_hooks('prepare_body', $prep_arr);
1345 $s = $prep_arr['html'];
1348 // Replace the blockquotes with quotes that are used in mails
1349 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1350 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1356 $arr = explode('[/attach],',$item['attach']);
1358 $as .= '<div class="body-attach">';
1359 foreach($arr as $r) {
1362 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1364 foreach($matches as $mtch) {
1367 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1368 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1370 $the_url = $mtch[1];
1372 if(strpos($mime, 'video') !== false) {
1375 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1376 '$baseurl' => $a->get_baseurl(),
1378 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1379 '$baseurl' => $a->get_baseurl(),
1383 $id = end(explode('/', $the_url));
1384 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1387 'title' => t('View Video'),
1394 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1396 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1397 $filesubtype = str_replace('.', '-', $filesubtype);
1401 $filesubtype = 'unkn';
1404 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1405 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1411 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1414 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1418 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1419 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1421 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1425 $as .= '<div class="clear"></div></div>';
1431 $spoilersearch = '<blockquote class="spoiler">';
1433 // Remove line breaks before the spoiler
1434 while ((strpos($s, "\n".$spoilersearch) !== false))
1435 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1436 while ((strpos($s, "<br />".$spoilersearch) !== false))
1437 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1439 while ((strpos($s, $spoilersearch) !== false)) {
1441 $pos = strpos($s, $spoilersearch);
1442 $rnd = random_string(8);
1443 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1444 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1445 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1448 // Look for quote with author
1449 $authorsearch = '<blockquote class="author">';
1451 while ((strpos($s, $authorsearch) !== false)) {
1453 $pos = strpos($s, $authorsearch);
1454 $rnd = random_string(8);
1455 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1456 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1457 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1460 $prep_arr = array('item' => $item, 'html' => $s);
1461 call_hooks('prepare_body_final', $prep_arr);
1463 return $prep_arr['html'];
1467 if(! function_exists('prepare_text')) {
1469 * Given a text string, convert from bbcode to html and add smilie icons.
1471 * @param string $text
1474 function prepare_text($text) {
1476 require_once('include/bbcode.php');
1478 if(stristr($text,'[nosmile]'))
1481 $s = smilies(bbcode($text));
1489 * return array with details for categories and folders for an item
1491 * @param array $item
1495 * [ // categories array
1497 * 'name': 'category name',
1498 * 'removeurl': 'url to remove this category',
1499 * 'first': 'is the first in this array? true/false',
1500 * 'last': 'is the last in this array? true/false',
1506 * 'name': 'folder name',
1507 * 'removeurl': 'url to remove this folder',
1508 * 'first': 'is the first in this array? true/false',
1509 * 'last': 'is the last in this array? true/false',
1515 function get_cats_and_terms($item) {
1518 $categories = array();
1521 $matches = false; $first = true;
1522 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1524 foreach($matches as $mtch) {
1525 $categories[] = array(
1526 'name' => xmlify(file_tag_decode($mtch[1])),
1528 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1535 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1538 if(local_user() == $item['uid']) {
1539 $matches = false; $first = true;
1540 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1542 foreach($matches as $mtch) {
1544 'name' => xmlify(file_tag_decode($mtch[1])),
1546 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1555 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1557 return array($categories, $folders);
1562 if(! function_exists('feed_hublinks')) {
1564 * return atom link elements for all of our hubs
1565 * @return string hub link xml elements
1567 function feed_hublinks() {
1569 $hub = get_config('system','huburl');
1573 $hubs = explode(',', $hub);
1575 foreach($hubs as $h) {
1579 if ($h === '[internal]')
1580 $h = $a->get_baseurl() . '/pubsubhubbub';
1581 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1589 if(! function_exists('feed_salmonlinks')) {
1591 * return atom link elements for salmon endpoints
1592 * @param string $nick user nickname
1593 * @return string salmon link xml elements
1595 function feed_salmonlinks($nick) {
1599 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1601 // old style links that status.net still needed as of 12/2010
1603 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1604 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1608 if(! function_exists('get_plink')) {
1610 * get private link for item
1611 * @param array $item
1612 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1614 function get_plink($item) {
1617 if ($a->user['nickname'] != "") {
1619 'href' => $a->get_baseurl()."/display/".$a->user['nickname']."/".$item['id'],
1620 'title' => t('link to source'),
1622 $ret["orig"] = $ret["href"];
1624 if (x($item,'plink'))
1625 $ret["href"] = $item['plink'];
1627 } elseif (x($item,'plink') && ($item['private'] != 1))
1629 'href' => $item['plink'],
1630 'orig' => $item['plink'],
1631 'title' => t('link to source'),
1636 //if (x($item,'plink') && ($item['private'] != 1))
1641 if(! function_exists('unamp')) {
1643 * replace html amp entity with amp char
1647 function unamp($s) {
1648 return str_replace('&', '&', $s);
1654 if(! function_exists('lang_selector')) {
1656 * get html for language selector
1657 * @global string $lang
1659 * @template lang_selector.tpl
1661 function lang_selector() {
1664 $langs = glob('view/*/strings.php');
1666 $lang_options = array();
1669 if(is_array($langs) && count($langs)) {
1671 if(! in_array('view/en/strings.php',$langs))
1672 $langs[] = 'view/en/';
1674 foreach($langs as $l) {
1676 $lang_options[""] = t('default');
1680 $ll = substr($ll,0,strrpos($ll,'/'));
1681 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1682 $lang_options[$ll]=$ll;
1686 $tpl = get_markup_template("lang_selector.tpl");
1687 $o = replace_macros($tpl, array(
1688 '$title' => t('Select an alternate language'),
1689 '$langs' => array($lang_options, $selected),
1696 if(! function_exists('return_bytes')) {
1698 * return number of bytes in size (K, M, G)
1699 * @param string $size_str
1702 function return_bytes ($size_str) {
1703 switch (substr ($size_str, -1))
1705 case 'M': case 'm': return (int)$size_str * 1048576;
1706 case 'K': case 'k': return (int)$size_str * 1024;
1707 case 'G': case 'g': return (int)$size_str * 1073741824;
1708 default: return $size_str;
1715 function generate_user_guid() {
1718 $guid = random_string(16);
1719 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1724 } while ($found == true );
1731 * @param boolean $strip_padding
1734 function base64url_encode($s, $strip_padding = false) {
1736 $s = strtr(base64_encode($s),'+/','-_');
1739 $s = str_replace('=','',$s);
1748 function base64url_decode($s) {
1751 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1756 * // Placeholder for new rev of salmon which strips base64 padding.
1757 * // PHP base64_decode handles the un-padded input without requiring this step
1758 * // Uncomment if you find you need it.
1761 * if(! strpos($s,'=')) {
1771 return base64_decode(strtr($s,'-_','+/'));
1775 if (!function_exists('str_getcsv')) {
1779 * @param string $input
1780 * @param string $delimiter
1781 * @param string $enclosure
1782 * @param string $escape
1783 * @param string $eol
1784 * @return boolean|array False on error, otherwise array[row][column]
1786 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1787 if (is_string($input) && !empty($input)) {
1789 $tmp = preg_split("/".$eol."/",$input);
1790 if (is_array($tmp) && !empty($tmp)) {
1791 while (list($line_num, $line) = each($tmp)) {
1792 if (preg_match("/".$escape.$enclosure."/",$line)) {
1793 while ($strlen = strlen($line)) {
1794 $pos_delimiter = strpos($line,$delimiter);
1795 $pos_enclosure_start = strpos($line,$enclosure);
1797 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1798 && ($pos_enclosure_start < $pos_delimiter)
1800 $enclosed_str = substr($line,1);
1801 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1802 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1803 $output[$line_num][] = $enclosed_str;
1804 $offset = $pos_enclosure_end+3;
1806 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1807 $output[$line_num][] = substr($line,0);
1808 $offset = strlen($line);
1810 $output[$line_num][] = substr($line,0,$pos_delimiter);
1812 !empty($pos_enclosure_start)
1813 && ($pos_enclosure_start < $pos_delimiter)
1815 ?$pos_enclosure_start
1819 $line = substr($line,$offset);
1822 $line = preg_split("/".$delimiter."/",$line);
1825 * Validating against pesky extra line breaks creating false rows.
1827 if (is_array($line) && !empty($line[0])) {
1828 $output[$line_num] = $line;
1843 * return div element with class 'clear'
1847 function cleardiv() {
1848 return '<div class="clear"></div>';
1852 function bb_translate_video($s) {
1855 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1857 foreach($matches as $mtch) {
1858 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1859 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1860 elseif(stristr($mtch[1],'vimeo'))
1861 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1867 function html2bb_video($s) {
1869 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1870 '[youtube]$2[/youtube]', $s);
1872 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1873 '[youtube]$2[/youtube]', $s);
1875 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1876 '[vimeo]$2[/vimeo]', $s);
1882 * apply xmlify() to all values of array $val, recursively
1886 function array_xmlify($val){
1887 if (is_bool($val)) return $val?"true":"false";
1888 if (is_array($val)) return array_map('array_xmlify', $val);
1889 return xmlify((string) $val);
1894 * transorm link href and img src from relative to absolute
1896 * @param string $text
1897 * @param string $base base url
1900 function reltoabs($text, $base)
1905 $base = rtrim($base,'/');
1907 $base2 = $base . "/";
1910 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1911 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1912 $text = preg_replace($pattern, $replace, $text);
1914 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1915 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1916 $text = preg_replace($pattern, $replace, $text);
1919 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1920 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1921 $text = preg_replace($pattern, $replace, $text);
1923 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1924 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1925 $text = preg_replace($pattern, $replace, $text);
1933 * get translated item type
1935 * @param array $itme
1938 function item_post_type($item) {
1939 if(intval($item['event-id']))
1941 if(strlen($item['resource-id']))
1943 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1944 return t('activity');
1945 if($item['id'] != $item['parent'])
1946 return t('comment');
1950 // post categories and "save to file" use the same item.file table for storage.
1951 // We will differentiate the different uses by wrapping categories in angle brackets
1952 // and save to file categories in square brackets.
1953 // To do this we need to escape these characters if they appear in our tag.
1955 function file_tag_encode($s) {
1956 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1959 function file_tag_decode($s) {
1960 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1963 function file_tag_file_query($table,$s,$type = 'file') {
1966 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1968 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1969 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1972 // ex. given music,video return <music><video> or [music][video]
1973 function file_tag_list_to_file($list,$type = 'file') {
1976 $list_array = explode(",",$list);
1977 if($type == 'file') {
1986 foreach($list_array as $item) {
1988 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1995 // ex. given <music><video>[friends], return music,video or friends
1996 function file_tag_file_to_list($file,$type = 'file') {
1999 if($type == 'file') {
2000 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
2003 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
2006 foreach($matches as $mtch) {
2009 $list .= file_tag_decode($mtch[1]);
2016 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
2017 // $file_old - categories previously associated with an item
2018 // $file_new - new list of categories for an item
2023 if($file_old == $file_new)
2026 $saved = get_pconfig($uid,'system','filetags');
2027 if(strlen($saved)) {
2028 if($type == 'file') {
2031 $termtype = TERM_FILE;
2036 $termtype = TERM_CATEGORY;
2039 $filetags_updated = $saved;
2041 // check for new tags to be added as filetags in pconfig
2042 $new_tags = array();
2043 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2045 foreach($check_new_tags as $tag) {
2046 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2050 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2052 // check for deleted tags to be removed from filetags in pconfig
2053 $deleted_tags = array();
2054 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2056 foreach($check_deleted_tags as $tag) {
2057 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2058 $deleted_tags[] = $tag;
2061 foreach($deleted_tags as $key => $tag) {
2062 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2064 intval(TERM_OBJ_POST),
2068 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2073 unset($deleted_tags[$key]);
2076 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2080 if($saved != $filetags_updated) {
2081 set_pconfig($uid,'system','filetags', $filetags_updated);
2086 if(strlen($file_new)) {
2087 set_pconfig($uid,'system','filetags', $file_new);
2092 function file_tag_save_file($uid,$item,$file) {
2093 require_once("include/files.php");
2098 $r = q("select file from item where id = %d and uid = %d limit 1",
2103 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2104 q("update item set file = '%s' where id = %d and uid = %d",
2105 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2110 create_files_from_item($item);
2112 $saved = get_pconfig($uid,'system','filetags');
2113 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2114 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2115 info( t('Item filed') );
2120 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2121 require_once("include/files.php");
2128 $pattern = '<' . file_tag_encode($file) . '>' ;
2129 $termtype = TERM_CATEGORY;
2131 $pattern = '[' . file_tag_encode($file) . ']' ;
2132 $termtype = TERM_FILE;
2136 $r = q("select file from item where id = %d and uid = %d limit 1",
2143 q("update item set file = '%s' where id = %d and uid = %d",
2144 dbesc(str_replace($pattern,'',$r[0]['file'])),
2149 create_files_from_item($item);
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 and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2161 $saved = get_pconfig($uid,'system','filetags');
2162 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2168 function normalise_openid($s) {
2169 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2173 function undo_post_tagging($s) {
2175 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2177 foreach($matches as $mtch) {
2178 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2184 function fix_mce_lf($s) {
2185 $s = str_replace("\r\n","\n",$s);
2186 // $s = str_replace("\n\n","\n",$s);
2191 function protect_sprintf($s) {
2192 return(str_replace('%','%%',$s));
2196 function is_a_date_arg($s) {
2200 if($i <= $y+1 && strpos($s,'-') == 4) {
2201 $m = intval(substr($s,5));
2202 if($m > 0 && $m <= 12)