3 require_once("include/template_processor.php");
4 require_once("include/friendica_smarty.php");
6 if(! function_exists('replace_macros')) {
8 * This is our template processor
10 * @param string|FriendicaSmarty $s the string requiring macro substitution,
11 * or an instance of FriendicaSmarty
12 * @param array $r key value pairs (search => replace)
13 * @return string substituted string
15 function replace_macros($s,$r) {
17 $stamp1 = microtime(true);
21 $t = $a->template_engine();
23 $output = $t->replace_macros($s,$r);
24 } catch (Exception $e) {
25 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
28 $a->save_timestamp($stamp1, "rendering");
34 // random string, there are 86 characters max in text mode, 128 for hex
37 define('RANDOM_STRING_HEX', 0x00 );
38 define('RANDOM_STRING_TEXT', 0x01 );
40 if(! function_exists('random_string')) {
41 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
42 // generate a bit of entropy and run it through the whirlpool
43 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
44 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
45 return(substr($s,0,$size));
48 if(! function_exists('notags')) {
50 * This is our primary input filter.
52 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
53 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
54 * after cleansing, and angle chars with the high bit set could get through as markup.
56 * This is now disabled because it was interfering with some legitimate unicode sequences
57 * and hopefully there aren't a lot of those browsers left.
59 * Use this on any text input where angle chars are not valid or permitted
60 * They will be replaced with safer brackets. This may be filtered further
61 * if these are not allowed either.
63 * @param string $string Input string
64 * @return string Filtered string
66 function notags($string) {
68 return(str_replace(array("<",">"), array('[',']'), $string));
70 // High-bit filter no longer used
71 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
76 if(! function_exists('escape_tags')) {
78 * use this on "body" or "content" input where angle chars shouldn't be removed,
79 * and allow them to be safely displayed.
80 * @param string $string
83 function escape_tags($string) {
85 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
89 // generate a string that's random, but usually pronounceable.
90 // used to generate initial passwords
92 if(! function_exists('autoname')) {
94 * generate a string that's random, but usually pronounceable.
95 * used to generate initial passwords
99 function autoname($len) {
104 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
105 if(mt_rand(0,5) == 4)
123 's','sc','sh','sm','sp','st',
131 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
132 'nd','ng','nk','nt','rn','rp','rt');
134 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
135 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
137 $start = mt_rand(0,2);
145 for ($x = 0; $x < $len; $x ++) {
146 $r = mt_rand(0,count($table) - 1);
149 if($table == $vowels)
150 $table = array_merge($cons,$midcons);
156 $word = substr($word,0,$len);
158 foreach($noend as $noe) {
159 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
160 $word = substr($word,0,-1);
164 if(substr($word,-1) == 'q')
165 $word = substr($word,0,-1);
170 // escape text ($str) for XML transport
171 // returns escaped text.
173 if(! function_exists('xmlify')) {
175 * escape text ($str) for XML transport
177 * @return string Escaped text.
179 function xmlify($str) {
182 $len = mb_strlen($str);
183 for($x = 0; $x < $len; $x ++) {
184 $char = mb_substr($str,$x,1);
214 $buffer = mb_ereg_replace("&", "&", $str);
215 $buffer = mb_ereg_replace("'", "'", $buffer);
216 $buffer = mb_ereg_replace('"', """, $buffer);
217 $buffer = mb_ereg_replace("<", "<", $buffer);
218 $buffer = mb_ereg_replace(">", ">", $buffer);
220 $buffer = htmlspecialchars($str, ENT_QUOTES);
221 $buffer = trim($buffer);
226 if(! function_exists('unxmlify')) {
229 * @param string $s xml escaped text
230 * @return string unescaped text
232 function unxmlify($s) {
233 // $ret = str_replace('&','&', $s);
234 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
235 /*$ret = mb_ereg_replace('&', '&', $s);
236 $ret = mb_ereg_replace(''', "'", $ret);
237 $ret = mb_ereg_replace('"', '"', $ret);
238 $ret = mb_ereg_replace('<', "<", $ret);
239 $ret = mb_ereg_replace('>', ">", $ret);
241 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
245 if(! function_exists('hex2bin')) {
247 * convenience wrapper, reverse the operation "bin2hex"
251 function hex2bin($s) {
252 if(! (is_string($s) && strlen($s)))
255 if(! ctype_xdigit($s)) {
259 return(pack("H*",$s));
263 if(! function_exists('paginate_data')) {
265 * Automatica pagination data.
267 * @param App $a App instance
268 * @param int $count [optional] item count (used with alt pager)
269 * @return Array data for pagination template
271 function paginate_data(&$a, $count=null) {
272 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
274 $stripped = str_replace('q=','',$stripped);
275 $stripped = trim($stripped,'/');
276 $pagenum = $a->pager['page'];
278 if (($a->page_offset != "") AND !strstr($stripped, "&offset="))
279 $stripped .= "&offset=".urlencode($a->page_offset);
280 if (!strpos($stripped, "?")) {
281 if ($pos = strpos($stripped, "&"))
282 $stripped = substr($stripped, 0, $pos)."?".substr($stripped, $pos + 1);
285 $url = $a->get_baseurl() . '/' . $stripped;
288 function _l(&$d, $name, $url, $text, $class="") {
290 $d[$name] = array('url'=>$url, 'text'=>$text, 'class'=>$class);
293 if (!is_null($count)){
295 if($a->pager['page']>1)
296 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('newer'));
298 _l($data, "next", $url.'&page='.($a->pager['page'] + 1), t('older'));
301 if($a->pager['total'] > $a->pager['itemspage']) {
302 if($a->pager['page'] != 1)
303 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('prev'));
305 _l($data, "first", $url."&page=1", t('first'));
308 $numpages = $a->pager['total'] / $a->pager['itemspage'];
311 $numstop = $numpages;
314 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
315 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
320 for($i = $numstart; $i <= $numstop; $i++){
321 if($i == $a->pager['page'])
322 _l($pages, $i, "#", $i, "current");
324 _l($pages, $i, $url."&page=$i", $i, "n");
327 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
328 if($i == $a->pager['page'])
329 _l($pages, $i, "#", $i, "current");
331 _l($pages, $i, $url."&page=$i", $i, "n");
334 $data['pages'] = $pages;
336 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
337 _l($data, "last", $url."&page=$lastpage", t('last'));
339 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
340 _l($data, "next", $url."&page=".($a->pager['page'] + 1), t('next'));
348 if(! function_exists('paginate')) {
350 * Automatic pagination.
352 * To use, get the count of total items.
353 * Then call $a->set_pager_total($number_items);
354 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
355 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
356 * (assuming there are enough items to paginate).
357 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
358 * will limit the results to the correct items for the current page.
359 * The actual page handling is then accomplished at the application layer.
361 * @param App $a App instance
362 * @return string html for pagination #FIXME remove html
364 function paginate(&$a) {
366 $data = paginate_data($a);
367 $tpl = get_markup_template("paginate.tpl");
368 return replace_macros($tpl, array("pager" => $data));
372 if(! function_exists('alt_pager')) {
375 * @param App $a App instance
377 * @return string html for pagination #FIXME remove html
379 function alt_pager(&$a, $i) {
381 $data = paginate_data($a, $i);
382 $tpl = get_markup_template("paginate.tpl");
383 return replace_macros($tpl, array('pager' => $data));
388 if(! function_exists('expand_acl')) {
390 * Turn user/group ACLs stored as angle bracketed text into arrays
395 function expand_acl($s) {
396 // turn string array of angle-bracketed elements into numeric array
397 // e.g. "<1><2><3>" => array(1,2,3);
401 $t = str_replace('<','',$s);
402 $a = explode('>',$t);
405 $ret[] = intval($aa);
411 if(! function_exists('sanitise_acl')) {
413 * Wrap ACL elements in angle brackets for storage
414 * @param string $item
416 function sanitise_acl(&$item) {
418 $item = '<' . intval(notags(trim($item))) . '>';
424 if(! function_exists('perms2str')) {
426 * Convert an ACL array to a storable string
428 * Normally ACL permissions will be an array.
429 * We'll also allow a comma-separated string.
431 * @param string|array $p
434 function perms2str($p) {
439 $tmp = explode(',',$p);
442 array_walk($tmp,'sanitise_acl');
443 $ret = implode('',$tmp);
449 if(! function_exists('item_new_uri')) {
451 * generate a guaranteed unique (for this domain) item ID for ATOM
452 * safe from birthday paradox
454 * @param string $hostname
458 function item_new_uri($hostname,$uid) {
462 $hash = random_string();
464 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
466 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
470 } while($dups == true);
474 // Generate a guaranteed unique photo ID.
475 // safe from birthday paradox
477 if(! function_exists('photo_new_resource')) {
479 * Generate a guaranteed unique photo ID.
480 * safe from birthday paradox
484 function photo_new_resource() {
488 $resource = hash('md5',uniqid(mt_rand(),true));
489 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
494 } while($found == true);
499 if(! function_exists('load_view_file')) {
502 * wrapper to load a view template, checking for alternate
503 * languages before falling back to the default
505 * @global string $lang
507 * @param string $s view name
510 function load_view_file($s) {
516 if(file_exists("$d/$lang/$b")) {
517 $stamp1 = microtime(true);
518 $content = file_get_contents("$d/$lang/$b");
519 $a->save_timestamp($stamp1, "file");
523 $theme = current_theme();
525 if(file_exists("$d/theme/$theme/$b")) {
526 $stamp1 = microtime(true);
527 $content = file_get_contents("$d/theme/$theme/$b");
528 $a->save_timestamp($stamp1, "file");
532 $stamp1 = microtime(true);
533 $content = file_get_contents($s);
534 $a->save_timestamp($stamp1, "file");
538 if(! function_exists('get_intltext_template')) {
540 * load a view template, checking for alternate
541 * languages before falling back to the default
543 * @global string $lang
544 * @param string $s view path
547 function get_intltext_template($s) {
552 if($a->theme['template_engine'] === 'smarty3')
553 $engine = "/smarty3";
558 if(file_exists("view/$lang$engine/$s")) {
559 $stamp1 = microtime(true);
560 $content = file_get_contents("view/$lang$engine/$s");
561 $a->save_timestamp($stamp1, "file");
563 } elseif(file_exists("view/en$engine/$s")) {
564 $stamp1 = microtime(true);
565 $content = file_get_contents("view/en$engine/$s");
566 $a->save_timestamp($stamp1, "file");
569 $stamp1 = microtime(true);
570 $content = file_get_contents("view$engine/$s");
571 $a->save_timestamp($stamp1, "file");
576 if(! function_exists('get_markup_template')) {
581 * @param string $root
584 function get_markup_template($s, $root = '') {
585 $stamp1 = microtime(true);
588 $t = $a->template_engine();
590 $template = $t->get_template_file($s, $root);
591 } catch (Exception $e) {
592 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
595 $a->save_timestamp($stamp1, "file");
600 if(! function_exists("get_template_file")) {
604 * @param string $filename
605 * @param string $root
608 function get_template_file($a, $filename, $root = '') {
609 $theme = current_theme();
611 // Make sure $root ends with a slash /
612 if($root !== '' && $root[strlen($root)-1] !== '/')
615 if(file_exists("{$root}view/theme/$theme/$filename"))
616 $template_file = "{$root}view/theme/$theme/$filename";
617 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
618 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
619 elseif (file_exists("{$root}/$filename"))
620 $template_file = "{$root}/$filename";
622 $template_file = "{$root}view/$filename";
624 return $template_file;
633 if(! function_exists('attribute_contains')) {
635 * for html,xml parsing - let's say you've got
636 * an attribute foobar="class1 class2 class3"
637 * and you want to find out if it contains 'class3'.
638 * you can't use a normal sub string search because you
639 * might match 'notclass3' and a regex to do the job is
640 * possible but a bit complicated.
641 * pass the attribute string as $attr and the attribute you
642 * are looking for as $s - returns true if found, otherwise false
644 * @param string $attr attribute value
645 * @param string $s string to search
646 * @return boolean True if found, False otherwise
648 function attribute_contains($attr,$s) {
649 $a = explode(' ', $attr);
650 if(count($a) && in_array($s,$a))
655 if(! function_exists('logger')) {
656 /* setup int->string log level map */
657 $LOGGER_LEVELS = array();
661 * LOGGER_NORMAL (default)
672 function logger($msg,$level = 0) {
673 // turn off logger in install mode
676 global $LOGGER_LEVELS;
678 if(($a->module == 'install') || (! ($db && $db->connected))) return;
680 if (count($LOGGER_LEVEL)==0){
681 foreach (get_defined_constants() as $k=>$v){
682 if (substr($k,0,7)=="LOGGER_") $LOGGER_LEVELS[$v] = substr($k,7,7);
686 $debugging = get_config('system','debugging');
687 $loglevel = intval(get_config('system','loglevel'));
688 $logfile = get_config('system','logfile');
690 if((! $debugging) || (! $logfile) || ($level > $loglevel))
693 $callers = debug_backtrace();
694 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
697 $LOGGER_LEVELS[$level],
698 basename($callers[0]['file']),
700 $callers[1]['function'],
704 $stamp1 = microtime(true);
705 @file_put_contents($logfile, $logline, FILE_APPEND);
706 $a->save_timestamp($stamp1, "file");
711 if(! function_exists('activity_match')) {
713 * Compare activity uri. Knows about activity namespace.
715 * @param string $haystack
716 * @param string $needle
719 function activity_match($haystack,$needle) {
720 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
726 if(! function_exists('get_tags')) {
728 * Pull out all #hashtags and @person tags from $s;
729 * We also get @person@domain.com - which would make
730 * the regex quite complicated as tags can also
731 * end a sentence. So we'll run through our results
732 * and strip the period from any tags which end with one.
733 * Returns array of tags found, or empty array.
738 function get_tags($s) {
741 // ignore anything in a code block
742 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
744 // Force line feeds at bbtags
745 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
747 // ignore anything in a bbtag
748 $s = preg_replace('/\[(.*?)\]/sm','',$s);
750 // Match full names against @tags including the space between first and last
751 // We will look these up afterward to see if they are full names or not recognisable.
753 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
754 foreach($match[1] as $mtch) {
755 if(strstr($mtch,"]")) {
756 // we might be inside a bbcode color tag - leave it alone
759 if(substr($mtch,-1,1) === '.')
760 $ret[] = substr($mtch,0,-1);
766 // Otherwise pull out single word tags. These can be @nickname, @first_last
769 if(preg_match_all('/([!#@][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
770 foreach($match[1] as $mtch) {
771 if(strstr($mtch,"]")) {
772 // we might be inside a bbcode color tag - leave it alone
775 if(substr($mtch,-1,1) === '.')
776 $mtch = substr($mtch,0,-1);
777 // ignore strictly numeric tags like #1
778 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
780 // try not to catch url fragments
781 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
792 if(! function_exists('qp')) {
794 * quick and dirty quoted_printable encoding
800 return str_replace ("%","=",rawurlencode($s));
805 if(! function_exists('get_mentions')) {
808 * @return string html for mentions #FIXME: remove html
810 function get_mentions($item) {
812 if(! strlen($item['tag']))
815 $arr = explode(',',$item['tag']);
816 foreach($arr as $x) {
818 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
819 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
820 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
826 if(! function_exists('contact_block')) {
828 * Get html for contact block.
830 * @template contact_block.tpl
831 * @hook contact_block_end (contacts=>array, output=>string)
834 function contact_block() {
838 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
844 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
846 $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",
847 intval($a->profile['uid'])
850 $total = intval($r[0]['total']);
853 $contacts = t('No contacts');
857 $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",
858 intval($a->profile['uid']),
862 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
865 $micropro[] = micropro($rr,true,'mpfriend');
870 $tpl = get_markup_template('contact_block.tpl');
871 $o = replace_macros($tpl, array(
872 '$contacts' => $contacts,
873 '$nickname' => $a->profile['nickname'],
874 '$viewcontacts' => t('View Contacts'),
875 '$micropro' => $micropro,
878 $arr = array('contacts' => $r, 'output' => $o);
880 call_hooks('contact_block_end', $arr);
885 if(! function_exists('micropro')) {
888 * @param array $contact
889 * @param boolean $redirect
890 * @param string $class
891 * @param boolean $textmode
892 * @return string #FIXME: remove html
894 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
897 $class = ' ' . $class;
899 $url = $contact['url'];
905 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
906 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
908 $url = $redirect_url;
909 $sparkle = ' sparkle';
914 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
918 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
919 . (($click) ? ' fakelink' : '') . '" '
920 . (($redir) ? ' target="redir" ' : '')
921 . (($url) ? ' href="' . $url . '"' : '') . $click
922 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
923 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
926 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
927 . (($click) ? ' fakelink' : '') . '" '
928 . (($redir) ? ' target="redir" ' : '')
929 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
930 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
931 . '" /></a></div>' . "\r\n";
937 if(! function_exists('search')) {
941 * @param string $s search query
942 * @param string $id html id
943 * @param string $url search url
944 * @param boolean $save show save search button
945 * @return string html for search box #FIXME: remove html
947 function search($s,$id='search-box',$url='/search',$save = false) {
949 $o = '<div id="' . $id . '">';
950 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
951 $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
952 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
954 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
955 $o .= '</form></div>';
959 if(! function_exists('valid_email')) {
961 * Check if $x is a valid email string
966 function valid_email($x){
968 if(get_config('system','disable_email_validation'))
971 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
977 if(! function_exists('linkify')) {
979 * Replace naked text hyperlink with HTML formatted hyperlink
983 function linkify($s) {
984 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
985 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
993 * @return array index is present tense verb
994 value is array containing past tense verb, translation of present, translation of past
995 * @hook poke_verbs pokes array
997 function get_poke_verbs() {
999 // index is present tense verb
1000 // value is array containing past tense verb, translation of present, translation of past
1003 'poke' => array( 'poked', t('poke'), t('poked')),
1004 'ping' => array( 'pinged', t('ping'), t('pinged')),
1005 'prod' => array( 'prodded', t('prod'), t('prodded')),
1006 'slap' => array( 'slapped', t('slap'), t('slapped')),
1007 'finger' => array( 'fingered', t('finger'), t('fingered')),
1008 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1010 call_hooks('poke_verbs', $arr);
1016 * @return array index is mood, value is translated mood
1017 * @hook mood_verbs moods array
1019 function get_mood_verbs() {
1022 'happy' => t('happy'),
1024 'mellow' => t('mellow'),
1025 'tired' => t('tired'),
1026 'perky' => t('perky'),
1027 'angry' => t('angry'),
1028 'stupefied' => t('stupified'),
1029 'puzzled' => t('puzzled'),
1030 'interested' => t('interested'),
1031 'bitter' => t('bitter'),
1032 'cheerful' => t('cheerful'),
1033 'alive' => t('alive'),
1034 'annoyed' => t('annoyed'),
1035 'anxious' => t('anxious'),
1036 'cranky' => t('cranky'),
1037 'disturbed' => t('disturbed'),
1038 'frustrated' => t('frustrated'),
1039 'motivated' => t('motivated'),
1040 'relaxed' => t('relaxed'),
1041 'surprised' => t('surprised'),
1044 call_hooks('mood_verbs', $arr);
1050 if(! function_exists('smilies')) {
1052 * Replaces text emoticons with graphical images
1054 * It is expected that this function will be called using HTML text.
1055 * We will escape text between HTML pre and code blocks from being
1058 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
1059 * function from being executed by the prepare_text() routine when preparing
1060 * bbcode source for HTML display
1063 * @param boolean $sample
1065 * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1067 function smilies($s, $sample = false) {
1070 if(intval(get_config('system','no_smilies'))
1071 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1074 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1075 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1116 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1117 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1118 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1119 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1120 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1121 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1122 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1123 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1124 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1125 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1126 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1127 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1128 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1129 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1130 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1131 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
1132 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
1133 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
1134 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
1135 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
1136 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1137 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1138 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1139 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1140 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1141 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1142 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1143 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1144 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1145 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1146 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1147 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1148 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
1149 '<a href="http://redmatrix.me/">red <img class="smiley" src="' . $a->get_baseurl() . '/images/rhash-16.png" alt="red" /></a>'
1152 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1153 call_hooks('smilie', $params);
1156 $s = '<div class="smiley-sample">';
1157 for($x = 0; $x < count($params['texts']); $x ++) {
1158 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1162 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
1163 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1166 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1167 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1173 function smile_encode($m) {
1174 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1177 function smile_decode($m) {
1178 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1183 * expand <3333 to the correct number of hearts
1188 function preg_heart($x) {
1190 if(strlen($x[1]) == 1)
1193 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1194 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1195 $r = str_replace($x[0],$t,$x[0]);
1200 if(! function_exists('day_translate')) {
1202 * Translate days and months names
1207 function day_translate($s) {
1208 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1209 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1212 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1213 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')),
1220 if(! function_exists('normalise_link')) {
1224 * @param string $url
1227 function normalise_link($url) {
1228 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1229 return(rtrim($ret,'/'));
1234 if(! function_exists('link_compare')) {
1236 * Compare two URLs to see if they are the same, but ignore
1237 * slight but hopefully insignificant differences such as if one
1238 * is https and the other isn't, or if one is www.something and
1239 * the other isn't - and also ignore case differences.
1241 * @param string $a first url
1242 * @param string $b second url
1243 * @return boolean True if the URLs match, otherwise False
1246 function link_compare($a,$b) {
1247 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1253 if(! function_exists('redir_private_images')) {
1255 * Find any non-embedded images in private items and add redir links to them
1258 * @param array $item
1260 function redir_private_images($a, &$item) {
1263 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1265 //logger("redir_private_images: matches = " . print_r($matches, true));
1266 foreach($matches as $mtch) {
1267 if(strpos($mtch[1], '/redir') !== false)
1270 if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1271 //logger("redir_private_images: redir");
1272 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1273 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1281 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1282 // If attach is true, also add icons for item attachments
1284 if(! function_exists('prepare_body')) {
1286 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1287 * If attach is true, also add icons for item attachments
1289 * @param array $item
1290 * @param boolean $attach
1291 * @return string item body html
1292 * @hook prepare_body_init item array before any work
1293 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1294 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1296 function prepare_body(&$item,$attach = false, $preview = false) {
1299 call_hooks('prepare_body_init', $item);
1301 $searchpath = $a->get_baseurl()."/search?tag=";
1304 $hashtags = array();
1305 $mentions = array();
1307 if (!get_config('system','suppress_tags')) {
1308 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1309 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1311 foreach($taglist as $tag) {
1313 if ($tag["url"] == "")
1314 $tag["url"] = $searchpath.strtolower($tag["term"]);
1316 if ($tag["type"] == TERM_HASHTAG) {
1317 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1319 } elseif ($tag["type"] == TERM_MENTION) {
1320 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1323 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1327 $item['tags'] = $tags;
1328 $item['hashtags'] = $hashtags;
1329 $item['mentions'] = $mentions;
1332 //$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
1333 $cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
1335 if (($cachefile != '')) {
1336 if (file_exists($cachefile)) {
1337 $stamp1 = microtime(true);
1338 $s = file_get_contents($cachefile);
1339 $a->save_timestamp($stamp1, "file");
1341 redir_private_images($a, $item);
1342 $s = prepare_text($item['body']);
1344 $stamp1 = microtime(true);
1345 file_put_contents($cachefile, $s);
1346 $a->save_timestamp($stamp1, "file");
1348 logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
1351 redir_private_images($a, $item);
1352 $s = prepare_text($item['body']);
1356 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1357 call_hooks('prepare_body', $prep_arr);
1358 $s = $prep_arr['html'];
1361 // Replace the blockquotes with quotes that are used in mails
1362 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1363 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1369 $arr = explode('[/attach],',$item['attach']);
1371 $as .= '<div class="body-attach">';
1372 foreach($arr as $r) {
1375 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1377 foreach($matches as $mtch) {
1380 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1381 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1383 $the_url = $mtch[1];
1385 if(strpos($mime, 'video') !== false) {
1388 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1389 '$baseurl' => $a->get_baseurl(),
1391 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1392 '$baseurl' => $a->get_baseurl(),
1396 $id = end(explode('/', $the_url));
1397 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1400 'title' => t('View Video'),
1407 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1409 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1410 $filesubtype = str_replace('.', '-', $filesubtype);
1414 $filesubtype = 'unkn';
1417 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1418 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1424 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1427 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1431 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1432 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1434 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1438 $as .= '<div class="clear"></div></div>';
1444 $spoilersearch = '<blockquote class="spoiler">';
1446 // Remove line breaks before the spoiler
1447 while ((strpos($s, "\n".$spoilersearch) !== false))
1448 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1449 while ((strpos($s, "<br />".$spoilersearch) !== false))
1450 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1452 while ((strpos($s, $spoilersearch) !== false)) {
1454 $pos = strpos($s, $spoilersearch);
1455 $rnd = random_string(8);
1456 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1457 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1458 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1461 // Look for quote with author
1462 $authorsearch = '<blockquote class="author">';
1464 while ((strpos($s, $authorsearch) !== false)) {
1466 $pos = strpos($s, $authorsearch);
1467 $rnd = random_string(8);
1468 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1469 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1470 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1473 $prep_arr = array('item' => $item, 'html' => $s);
1474 call_hooks('prepare_body_final', $prep_arr);
1476 return $prep_arr['html'];
1480 if(! function_exists('prepare_text')) {
1482 * Given a text string, convert from bbcode to html and add smilie icons.
1484 * @param string $text
1487 function prepare_text($text) {
1489 require_once('include/bbcode.php');
1491 if(stristr($text,'[nosmile]'))
1494 $s = smilies(bbcode($text));
1502 * return array with details for categories and folders for an item
1504 * @param array $item
1508 * [ // categories array
1510 * 'name': 'category name',
1511 * 'removeurl': 'url to remove this category',
1512 * 'first': 'is the first in this array? true/false',
1513 * 'last': 'is the last in this array? true/false',
1519 * 'name': 'folder name',
1520 * 'removeurl': 'url to remove this folder',
1521 * 'first': 'is the first in this array? true/false',
1522 * 'last': 'is the last in this array? true/false',
1528 function get_cats_and_terms($item) {
1531 $categories = array();
1534 $matches = false; $first = true;
1535 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1537 foreach($matches as $mtch) {
1538 $categories[] = array(
1539 'name' => xmlify(file_tag_decode($mtch[1])),
1541 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1548 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1551 if(local_user() == $item['uid']) {
1552 $matches = false; $first = true;
1553 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1555 foreach($matches as $mtch) {
1557 'name' => xmlify(file_tag_decode($mtch[1])),
1559 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1568 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1570 return array($categories, $folders);
1575 if(! function_exists('feed_hublinks')) {
1577 * return atom link elements for all of our hubs
1578 * @return string hub link xml elements
1580 function feed_hublinks() {
1582 $hub = get_config('system','huburl');
1586 $hubs = explode(',', $hub);
1588 foreach($hubs as $h) {
1592 if ($h === '[internal]')
1593 $h = $a->get_baseurl() . '/pubsubhubbub';
1594 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1602 if(! function_exists('feed_salmonlinks')) {
1604 * return atom link elements for salmon endpoints
1605 * @param string $nick user nickname
1606 * @return string salmon link xml elements
1608 function feed_salmonlinks($nick) {
1612 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1614 // old style links that status.net still needed as of 12/2010
1616 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1617 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1621 if(! function_exists('get_plink')) {
1623 * get private link for item
1624 * @param array $item
1625 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1627 function get_plink($item) {
1630 if ($a->user['nickname'] != "") {
1632 'href' => $a->get_baseurl()."/display/".$a->user['nickname']."/".$item['id'],
1633 'title' => t('link to source'),
1635 $ret["orig"] = $ret["href"];
1637 if (x($item,'plink'))
1638 $ret["href"] = $item['plink'];
1640 } elseif (x($item,'plink') && ($item['private'] != 1))
1642 'href' => $item['plink'],
1643 'orig' => $item['plink'],
1644 'title' => t('link to source'),
1649 //if (x($item,'plink') && ($item['private'] != 1))
1654 if(! function_exists('unamp')) {
1656 * replace html amp entity with amp char
1660 function unamp($s) {
1661 return str_replace('&', '&', $s);
1667 if(! function_exists('lang_selector')) {
1669 * get html for language selector
1670 * @global string $lang
1672 * @template lang_selector.tpl
1674 function lang_selector() {
1677 $langs = glob('view/*/strings.php');
1679 $lang_options = array();
1682 if(is_array($langs) && count($langs)) {
1684 if(! in_array('view/en/strings.php',$langs))
1685 $langs[] = 'view/en/';
1687 foreach($langs as $l) {
1689 $lang_options[""] = t('default');
1693 $ll = substr($ll,0,strrpos($ll,'/'));
1694 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1695 $lang_options[$ll]=$ll;
1699 $tpl = get_markup_template("lang_selector.tpl");
1700 $o = replace_macros($tpl, array(
1701 '$title' => t('Select an alternate language'),
1702 '$langs' => array($lang_options, $selected),
1709 if(! function_exists('return_bytes')) {
1711 * return number of bytes in size (K, M, G)
1712 * @param string $size_str
1715 function return_bytes ($size_str) {
1716 switch (substr ($size_str, -1))
1718 case 'M': case 'm': return (int)$size_str * 1048576;
1719 case 'K': case 'k': return (int)$size_str * 1024;
1720 case 'G': case 'g': return (int)$size_str * 1073741824;
1721 default: return $size_str;
1728 function generate_user_guid() {
1731 $guid = random_string(16);
1732 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1737 } while ($found == true );
1744 * @param boolean $strip_padding
1747 function base64url_encode($s, $strip_padding = false) {
1749 $s = strtr(base64_encode($s),'+/','-_');
1752 $s = str_replace('=','',$s);
1761 function base64url_decode($s) {
1764 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1769 * // Placeholder for new rev of salmon which strips base64 padding.
1770 * // PHP base64_decode handles the un-padded input without requiring this step
1771 * // Uncomment if you find you need it.
1774 * if(! strpos($s,'=')) {
1784 return base64_decode(strtr($s,'-_','+/'));
1788 if (!function_exists('str_getcsv')) {
1792 * @param string $input
1793 * @param string $delimiter
1794 * @param string $enclosure
1795 * @param string $escape
1796 * @param string $eol
1797 * @return boolean|array False on error, otherwise array[row][column]
1799 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1800 if (is_string($input) && !empty($input)) {
1802 $tmp = preg_split("/".$eol."/",$input);
1803 if (is_array($tmp) && !empty($tmp)) {
1804 while (list($line_num, $line) = each($tmp)) {
1805 if (preg_match("/".$escape.$enclosure."/",$line)) {
1806 while ($strlen = strlen($line)) {
1807 $pos_delimiter = strpos($line,$delimiter);
1808 $pos_enclosure_start = strpos($line,$enclosure);
1810 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1811 && ($pos_enclosure_start < $pos_delimiter)
1813 $enclosed_str = substr($line,1);
1814 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1815 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1816 $output[$line_num][] = $enclosed_str;
1817 $offset = $pos_enclosure_end+3;
1819 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1820 $output[$line_num][] = substr($line,0);
1821 $offset = strlen($line);
1823 $output[$line_num][] = substr($line,0,$pos_delimiter);
1825 !empty($pos_enclosure_start)
1826 && ($pos_enclosure_start < $pos_delimiter)
1828 ?$pos_enclosure_start
1832 $line = substr($line,$offset);
1835 $line = preg_split("/".$delimiter."/",$line);
1838 * Validating against pesky extra line breaks creating false rows.
1840 if (is_array($line) && !empty($line[0])) {
1841 $output[$line_num] = $line;
1856 * return div element with class 'clear'
1860 function cleardiv() {
1861 return '<div class="clear"></div>';
1865 function bb_translate_video($s) {
1868 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1870 foreach($matches as $mtch) {
1871 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1872 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1873 elseif(stristr($mtch[1],'vimeo'))
1874 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1880 function html2bb_video($s) {
1882 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1883 '[youtube]$2[/youtube]', $s);
1885 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1886 '[youtube]$2[/youtube]', $s);
1888 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1889 '[vimeo]$2[/vimeo]', $s);
1895 * apply xmlify() to all values of array $val, recursively
1899 function array_xmlify($val){
1900 if (is_bool($val)) return $val?"true":"false";
1901 if (is_array($val)) return array_map('array_xmlify', $val);
1902 return xmlify((string) $val);
1907 * transorm link href and img src from relative to absolute
1909 * @param string $text
1910 * @param string $base base url
1913 function reltoabs($text, $base)
1918 $base = rtrim($base,'/');
1920 $base2 = $base . "/";
1923 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1924 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1925 $text = preg_replace($pattern, $replace, $text);
1927 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1928 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1929 $text = preg_replace($pattern, $replace, $text);
1932 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1933 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1934 $text = preg_replace($pattern, $replace, $text);
1936 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1937 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1938 $text = preg_replace($pattern, $replace, $text);
1946 * get translated item type
1948 * @param array $itme
1951 function item_post_type($item) {
1952 if(intval($item['event-id']))
1954 if(strlen($item['resource-id']))
1956 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1957 return t('activity');
1958 if($item['id'] != $item['parent'])
1959 return t('comment');
1963 // post categories and "save to file" use the same item.file table for storage.
1964 // We will differentiate the different uses by wrapping categories in angle brackets
1965 // and save to file categories in square brackets.
1966 // To do this we need to escape these characters if they appear in our tag.
1968 function file_tag_encode($s) {
1969 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1972 function file_tag_decode($s) {
1973 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1976 function file_tag_file_query($table,$s,$type = 'file') {
1979 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1981 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1982 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1985 // ex. given music,video return <music><video> or [music][video]
1986 function file_tag_list_to_file($list,$type = 'file') {
1989 $list_array = explode(",",$list);
1990 if($type == 'file') {
1999 foreach($list_array as $item) {
2001 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
2008 // ex. given <music><video>[friends], return music,video or friends
2009 function file_tag_file_to_list($file,$type = 'file') {
2012 if($type == 'file') {
2013 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
2016 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
2019 foreach($matches as $mtch) {
2022 $list .= file_tag_decode($mtch[1]);
2029 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
2030 // $file_old - categories previously associated with an item
2031 // $file_new - new list of categories for an item
2036 if($file_old == $file_new)
2039 $saved = get_pconfig($uid,'system','filetags');
2040 if(strlen($saved)) {
2041 if($type == 'file') {
2044 $termtype = TERM_FILE;
2049 $termtype = TERM_CATEGORY;
2052 $filetags_updated = $saved;
2054 // check for new tags to be added as filetags in pconfig
2055 $new_tags = array();
2056 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2058 foreach($check_new_tags as $tag) {
2059 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2063 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2065 // check for deleted tags to be removed from filetags in pconfig
2066 $deleted_tags = array();
2067 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2069 foreach($check_deleted_tags as $tag) {
2070 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2071 $deleted_tags[] = $tag;
2074 foreach($deleted_tags as $key => $tag) {
2075 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2077 intval(TERM_OBJ_POST),
2081 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2086 unset($deleted_tags[$key]);
2089 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2093 if($saved != $filetags_updated) {
2094 set_pconfig($uid,'system','filetags', $filetags_updated);
2099 if(strlen($file_new)) {
2100 set_pconfig($uid,'system','filetags', $file_new);
2105 function file_tag_save_file($uid,$item,$file) {
2106 require_once("include/files.php");
2111 $r = q("select file from item where id = %d and uid = %d limit 1",
2116 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2117 q("update item set file = '%s' where id = %d and uid = %d",
2118 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2123 create_files_from_item($item);
2125 $saved = get_pconfig($uid,'system','filetags');
2126 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2127 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2128 info( t('Item filed') );
2133 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2134 require_once("include/files.php");
2141 $pattern = '<' . file_tag_encode($file) . '>' ;
2142 $termtype = TERM_CATEGORY;
2144 $pattern = '[' . file_tag_encode($file) . ']' ;
2145 $termtype = TERM_FILE;
2149 $r = q("select file from item where id = %d and uid = %d limit 1",
2156 q("update item set file = '%s' where id = %d and uid = %d",
2157 dbesc(str_replace($pattern,'',$r[0]['file'])),
2162 create_files_from_item($item);
2164 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2166 intval(TERM_OBJ_POST),
2170 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2174 $saved = get_pconfig($uid,'system','filetags');
2175 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2181 function normalise_openid($s) {
2182 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2186 function undo_post_tagging($s) {
2188 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2190 foreach($matches as $mtch) {
2191 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2197 function fix_mce_lf($s) {
2198 $s = str_replace("\r\n","\n",$s);
2199 // $s = str_replace("\n\n","\n",$s);
2204 function protect_sprintf($s) {
2205 return(str_replace('%','%%',$s));
2209 function is_a_date_arg($s) {
2213 if($i <= $y+1 && strpos($s,'-') == 4) {
2214 $m = intval(substr($s,5));
2215 if($m > 0 && $m <= 12)