3 require_once("include/template_processor.php");
4 require_once("include/friendica_smarty.php");
5 require_once("mod/proxy.php");
7 if(! function_exists('replace_macros')) {
9 * This is our template processor
11 * @param string|FriendicaSmarty $s the string requiring macro substitution,
12 * or an instance of FriendicaSmarty
13 * @param array $r key value pairs (search => replace)
14 * @return string substituted string
16 function replace_macros($s,$r) {
18 $stamp1 = microtime(true);
22 $t = $a->template_engine();
24 $output = $t->replace_macros($s,$r);
25 } catch (Exception $e) {
26 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
29 $a->save_timestamp($stamp1, "rendering");
35 // random string, there are 86 characters max in text mode, 128 for hex
38 define('RANDOM_STRING_HEX', 0x00 );
39 define('RANDOM_STRING_TEXT', 0x01 );
41 if(! function_exists('random_string')) {
42 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
43 // generate a bit of entropy and run it through the whirlpool
44 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
45 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
46 return(substr($s,0,$size));
49 if(! function_exists('notags')) {
51 * This is our primary input filter.
53 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
54 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
55 * after cleansing, and angle chars with the high bit set could get through as markup.
57 * This is now disabled because it was interfering with some legitimate unicode sequences
58 * and hopefully there aren't a lot of those browsers left.
60 * Use this on any text input where angle chars are not valid or permitted
61 * They will be replaced with safer brackets. This may be filtered further
62 * if these are not allowed either.
64 * @param string $string Input string
65 * @return string Filtered string
67 function notags($string) {
69 return(str_replace(array("<",">"), array('[',']'), $string));
71 // High-bit filter no longer used
72 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
77 if(! function_exists('escape_tags')) {
79 * use this on "body" or "content" input where angle chars shouldn't be removed,
80 * and allow them to be safely displayed.
81 * @param string $string
84 function escape_tags($string) {
86 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
90 // generate a string that's random, but usually pronounceable.
91 // used to generate initial passwords
93 if(! function_exists('autoname')) {
95 * generate a string that's random, but usually pronounceable.
96 * used to generate initial passwords
100 function autoname($len) {
105 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
106 if(mt_rand(0,5) == 4)
124 's','sc','sh','sm','sp','st',
132 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
133 'nd','ng','nk','nt','rn','rp','rt');
135 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
136 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
138 $start = mt_rand(0,2);
146 for ($x = 0; $x < $len; $x ++) {
147 $r = mt_rand(0,count($table) - 1);
150 if($table == $vowels)
151 $table = array_merge($cons,$midcons);
157 $word = substr($word,0,$len);
159 foreach($noend as $noe) {
160 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
161 $word = substr($word,0,-1);
165 if(substr($word,-1) == 'q')
166 $word = substr($word,0,-1);
171 // escape text ($str) for XML transport
172 // returns escaped text.
174 if(! function_exists('xmlify')) {
176 * escape text ($str) for XML transport
178 * @return string Escaped text.
180 function xmlify($str) {
183 $len = mb_strlen($str);
184 for($x = 0; $x < $len; $x ++) {
185 $char = mb_substr($str,$x,1);
215 $buffer = mb_ereg_replace("&", "&", $str);
216 $buffer = mb_ereg_replace("'", "'", $buffer);
217 $buffer = mb_ereg_replace('"', """, $buffer);
218 $buffer = mb_ereg_replace("<", "<", $buffer);
219 $buffer = mb_ereg_replace(">", ">", $buffer);
221 $buffer = htmlspecialchars($str, ENT_QUOTES);
222 $buffer = trim($buffer);
227 if(! function_exists('unxmlify')) {
230 * @param string $s xml escaped text
231 * @return string unescaped text
233 function unxmlify($s) {
234 // $ret = str_replace('&','&', $s);
235 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
236 /*$ret = mb_ereg_replace('&', '&', $s);
237 $ret = mb_ereg_replace(''', "'", $ret);
238 $ret = mb_ereg_replace('"', '"', $ret);
239 $ret = mb_ereg_replace('<', "<", $ret);
240 $ret = mb_ereg_replace('>', ">", $ret);
242 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
246 if(! function_exists('hex2bin')) {
248 * convenience wrapper, reverse the operation "bin2hex"
252 function hex2bin($s) {
253 if(! (is_string($s) && strlen($s)))
256 if(! ctype_xdigit($s)) {
260 return(pack("H*",$s));
264 if(! function_exists('paginate_data')) {
266 * Automatica pagination data.
268 * @param App $a App instance
269 * @param int $count [optional] item count (used with alt pager)
270 * @return Array data for pagination template
272 function paginate_data(&$a, $count=null) {
273 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
275 $stripped = str_replace('q=','',$stripped);
276 $stripped = trim($stripped,'/');
277 $pagenum = $a->pager['page'];
279 if (($a->page_offset != "") AND !preg_match('/[?&].offset=/', $stripped))
280 $stripped .= "&offset=".urlencode($a->page_offset);
282 $url = $a->get_baseurl() . '/' . $stripped;
285 function _l(&$d, $name, $url, $text, $class="") {
286 if (!strpos($url, "?")) {
287 if ($pos = strpos($url, "&"))
288 $url = substr($url, 0, $pos)."?".substr($url, $pos + 1);
291 $d[$name] = array('url'=>$url, 'text'=>$text, 'class'=>$class);
294 if (!is_null($count)){
296 if($a->pager['page']>1)
297 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('newer'));
299 _l($data, "next", $url.'&page='.($a->pager['page'] + 1), t('older'));
302 if($a->pager['total'] > $a->pager['itemspage']) {
303 if($a->pager['page'] != 1)
304 _l($data, "prev", $url.'&page='.($a->pager['page'] - 1), t('prev'));
306 _l($data, "first", $url."&page=1", t('first'));
309 $numpages = $a->pager['total'] / $a->pager['itemspage'];
312 $numstop = $numpages;
315 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
316 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
321 for($i = $numstart; $i <= $numstop; $i++){
322 if($i == $a->pager['page'])
323 _l($pages, $i, "#", $i, "current");
325 _l($pages, $i, $url."&page=$i", $i, "n");
328 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
329 if($i == $a->pager['page'])
330 _l($pages, $i, "#", $i, "current");
332 _l($pages, $i, $url."&page=$i", $i, "n");
335 $data['pages'] = $pages;
337 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
338 _l($data, "last", $url."&page=$lastpage", t('last'));
340 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
341 _l($data, "next", $url."&page=".($a->pager['page'] + 1), t('next'));
349 if(! function_exists('paginate')) {
351 * Automatic pagination.
353 * To use, get the count of total items.
354 * Then call $a->set_pager_total($number_items);
355 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
356 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
357 * (assuming there are enough items to paginate).
358 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
359 * will limit the results to the correct items for the current page.
360 * The actual page handling is then accomplished at the application layer.
362 * @param App $a App instance
363 * @return string html for pagination #FIXME remove html
365 function paginate(&$a) {
367 $data = paginate_data($a);
368 $tpl = get_markup_template("paginate.tpl");
369 return replace_macros($tpl, array("pager" => $data));
373 if(! function_exists('alt_pager')) {
376 * @param App $a App instance
378 * @return string html for pagination #FIXME remove html
380 function alt_pager(&$a, $i) {
382 $data = paginate_data($a, $i);
383 $tpl = get_markup_template("paginate.tpl");
384 return replace_macros($tpl, array('pager' => $data));
389 if(! function_exists('expand_acl')) {
391 * Turn user/group ACLs stored as angle bracketed text into arrays
396 function expand_acl($s) {
397 // turn string array of angle-bracketed elements into numeric array
398 // e.g. "<1><2><3>" => array(1,2,3);
402 $t = str_replace('<','',$s);
403 $a = explode('>',$t);
406 $ret[] = intval($aa);
412 if(! function_exists('sanitise_acl')) {
414 * Wrap ACL elements in angle brackets for storage
415 * @param string $item
417 function sanitise_acl(&$item) {
419 $item = '<' . intval(notags(trim($item))) . '>';
425 if(! function_exists('perms2str')) {
427 * Convert an ACL array to a storable string
429 * Normally ACL permissions will be an array.
430 * We'll also allow a comma-separated string.
432 * @param string|array $p
435 function perms2str($p) {
440 $tmp = explode(',',$p);
443 array_walk($tmp,'sanitise_acl');
444 $ret = implode('',$tmp);
450 if(! function_exists('item_new_uri')) {
452 * generate a guaranteed unique (for this domain) item ID for ATOM
453 * safe from birthday paradox
455 * @param string $hostname
459 function item_new_uri($hostname,$uid) {
463 $hash = random_string();
465 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
467 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
471 } while($dups == true);
475 // Generate a guaranteed unique photo ID.
476 // safe from birthday paradox
478 if(! function_exists('photo_new_resource')) {
480 * Generate a guaranteed unique photo ID.
481 * safe from birthday paradox
485 function photo_new_resource() {
489 $resource = hash('md5',uniqid(mt_rand(),true));
490 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
495 } while($found == true);
500 if(! function_exists('load_view_file')) {
503 * wrapper to load a view template, checking for alternate
504 * languages before falling back to the default
506 * @global string $lang
508 * @param string $s view name
511 function load_view_file($s) {
517 if(file_exists("$d/$lang/$b")) {
518 $stamp1 = microtime(true);
519 $content = file_get_contents("$d/$lang/$b");
520 $a->save_timestamp($stamp1, "file");
524 $theme = current_theme();
526 if(file_exists("$d/theme/$theme/$b")) {
527 $stamp1 = microtime(true);
528 $content = file_get_contents("$d/theme/$theme/$b");
529 $a->save_timestamp($stamp1, "file");
533 $stamp1 = microtime(true);
534 $content = file_get_contents($s);
535 $a->save_timestamp($stamp1, "file");
539 if(! function_exists('get_intltext_template')) {
541 * load a view template, checking for alternate
542 * languages before falling back to the default
544 * @global string $lang
545 * @param string $s view path
548 function get_intltext_template($s) {
553 if($a->theme['template_engine'] === 'smarty3')
554 $engine = "/smarty3";
559 if(file_exists("view/$lang$engine/$s")) {
560 $stamp1 = microtime(true);
561 $content = file_get_contents("view/$lang$engine/$s");
562 $a->save_timestamp($stamp1, "file");
564 } elseif(file_exists("view/en$engine/$s")) {
565 $stamp1 = microtime(true);
566 $content = file_get_contents("view/en$engine/$s");
567 $a->save_timestamp($stamp1, "file");
570 $stamp1 = microtime(true);
571 $content = file_get_contents("view$engine/$s");
572 $a->save_timestamp($stamp1, "file");
577 if(! function_exists('get_markup_template')) {
582 * @param string $root
585 function get_markup_template($s, $root = '') {
586 $stamp1 = microtime(true);
589 $t = $a->template_engine();
591 $template = $t->get_template_file($s, $root);
592 } catch (Exception $e) {
593 echo "<pre><b>".__function__."</b>: ".$e->getMessage()."</pre>"; killme();
596 $a->save_timestamp($stamp1, "file");
601 if(! function_exists("get_template_file")) {
605 * @param string $filename
606 * @param string $root
609 function get_template_file($a, $filename, $root = '') {
610 $theme = current_theme();
612 // Make sure $root ends with a slash /
613 if($root !== '' && $root[strlen($root)-1] !== '/')
616 if(file_exists("{$root}view/theme/$theme/$filename"))
617 $template_file = "{$root}view/theme/$theme/$filename";
618 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
619 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
620 elseif (file_exists("{$root}/$filename"))
621 $template_file = "{$root}/$filename";
623 $template_file = "{$root}view/$filename";
625 return $template_file;
634 if(! function_exists('attribute_contains')) {
636 * for html,xml parsing - let's say you've got
637 * an attribute foobar="class1 class2 class3"
638 * and you want to find out if it contains 'class3'.
639 * you can't use a normal sub string search because you
640 * might match 'notclass3' and a regex to do the job is
641 * possible but a bit complicated.
642 * pass the attribute string as $attr and the attribute you
643 * are looking for as $s - returns true if found, otherwise false
645 * @param string $attr attribute value
646 * @param string $s string to search
647 * @return boolean True if found, False otherwise
649 function attribute_contains($attr,$s) {
650 $a = explode(' ', $attr);
651 if(count($a) && in_array($s,$a))
656 if(! function_exists('logger')) {
657 /* setup int->string log level map */
658 $LOGGER_LEVELS = array();
662 * LOGGER_NORMAL (default)
673 function logger($msg,$level = 0) {
674 // turn off logger in install mode
677 global $LOGGER_LEVELS;
679 if(($a->module == 'install') || (! ($db && $db->connected))) return;
681 if (count($LOGGER_LEVELS)==0){
682 foreach (get_defined_constants() as $k=>$v){
683 if (substr($k,0,7)=="LOGGER_")
684 $LOGGER_LEVELS[$v] = substr($k,7,7);
688 $debugging = get_config('system','debugging');
689 $loglevel = intval(get_config('system','loglevel'));
690 $logfile = get_config('system','logfile');
692 if((! $debugging) || (! $logfile) || ($level > $loglevel))
695 $callers = debug_backtrace();
696 $logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
699 $LOGGER_LEVELS[$level],
700 basename($callers[0]['file']),
702 $callers[1]['function'],
706 $stamp1 = microtime(true);
707 @file_put_contents($logfile, $logline, FILE_APPEND);
708 $a->save_timestamp($stamp1, "file");
713 if(! function_exists('activity_match')) {
715 * Compare activity uri. Knows about activity namespace.
717 * @param string $haystack
718 * @param string $needle
721 function activity_match($haystack,$needle) {
722 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
728 if(! function_exists('get_tags')) {
730 * Pull out all #hashtags and @person tags from $s;
731 * We also get @person@domain.com - which would make
732 * the regex quite complicated as tags can also
733 * end a sentence. So we'll run through our results
734 * and strip the period from any tags which end with one.
735 * Returns array of tags found, or empty array.
740 function get_tags($s) {
743 // ignore anything in a code block
744 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
746 // Force line feeds at bbtags
747 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
749 // ignore anything in a bbtag
750 $s = preg_replace('/\[(.*?)\]/sm','',$s);
752 // Match full names against @tags including the space between first and last
753 // We will look these up afterward to see if they are full names or not recognisable.
755 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
756 foreach($match[1] as $mtch) {
757 if(strstr($mtch,"]")) {
758 // we might be inside a bbcode color tag - leave it alone
761 if(substr($mtch,-1,1) === '.')
762 $ret[] = substr($mtch,0,-1);
768 // Otherwise pull out single word tags. These can be @nickname, @first_last
771 if(preg_match_all('/([!#@][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
772 foreach($match[1] as $mtch) {
773 if(strstr($mtch,"]")) {
774 // we might be inside a bbcode color tag - leave it alone
777 if(substr($mtch,-1,1) === '.')
778 $mtch = substr($mtch,0,-1);
779 // ignore strictly numeric tags like #1
780 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
782 // try not to catch url fragments
783 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
794 if(! function_exists('qp')) {
796 * quick and dirty quoted_printable encoding
802 return str_replace ("%","=",rawurlencode($s));
807 if(! function_exists('get_mentions')) {
810 * @return string html for mentions #FIXME: remove html
812 function get_mentions($item) {
814 if(! strlen($item['tag']))
817 $arr = explode(',',$item['tag']);
818 foreach($arr as $x) {
820 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
821 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
822 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
828 if(! function_exists('contact_block')) {
830 * Get html for contact block.
832 * @template contact_block.tpl
833 * @hook contact_block_end (contacts=>array, output=>string)
836 function contact_block() {
840 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
846 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
848 $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",
849 intval($a->profile['uid'])
852 $total = intval($r[0]['total']);
855 $contacts = t('No contacts');
859 $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",
860 intval($a->profile['uid']),
864 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
867 $micropro[] = micropro($rr,true,'mpfriend');
872 $tpl = get_markup_template('contact_block.tpl');
873 $o = replace_macros($tpl, array(
874 '$contacts' => $contacts,
875 '$nickname' => $a->profile['nickname'],
876 '$viewcontacts' => t('View Contacts'),
877 '$micropro' => $micropro,
880 $arr = array('contacts' => $r, 'output' => $o);
882 call_hooks('contact_block_end', $arr);
887 if(! function_exists('micropro')) {
890 * @param array $contact
891 * @param boolean $redirect
892 * @param string $class
893 * @param boolean $textmode
894 * @return string #FIXME: remove html
896 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
899 $class = ' ' . $class;
901 $url = $contact['url'];
907 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
908 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
910 $url = $redirect_url;
911 $sparkle = ' sparkle';
916 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
920 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
921 . (($click) ? ' fakelink' : '') . '" '
922 . (($redir) ? ' target="redir" ' : '')
923 . (($url) ? ' href="' . $url . '"' : '') . $click
924 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
925 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
928 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
929 . (($click) ? ' fakelink' : '') . '" '
930 . (($redir) ? ' target="redir" ' : '')
931 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
932 . proxy_url($contact['micro']) . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
933 . '" /></a></div>' . "\r\n";
939 if(! function_exists('search')) {
943 * @param string $s search query
944 * @param string $id html id
945 * @param string $url search url
946 * @param boolean $save show save search button
947 * @return string html for search box #FIXME: remove html
949 function search($s,$id='search-box',$url='/search',$save = false) {
951 $o = '<div id="' . $id . '">';
952 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
953 $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
954 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
956 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
957 $o .= '</form></div>';
961 if(! function_exists('valid_email')) {
963 * Check if $x is a valid email string
968 function valid_email($x){
970 if(get_config('system','disable_email_validation'))
973 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
979 if(! function_exists('linkify')) {
981 * Replace naked text hyperlink with HTML formatted hyperlink
985 function linkify($s) {
986 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
987 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
995 * @return array index is present tense verb
996 value is array containing past tense verb, translation of present, translation of past
997 * @hook poke_verbs pokes array
999 function get_poke_verbs() {
1001 // index is present tense verb
1002 // value is array containing past tense verb, translation of present, translation of past
1005 'poke' => array( 'poked', t('poke'), t('poked')),
1006 'ping' => array( 'pinged', t('ping'), t('pinged')),
1007 'prod' => array( 'prodded', t('prod'), t('prodded')),
1008 'slap' => array( 'slapped', t('slap'), t('slapped')),
1009 'finger' => array( 'fingered', t('finger'), t('fingered')),
1010 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
1012 call_hooks('poke_verbs', $arr);
1018 * @return array index is mood, value is translated mood
1019 * @hook mood_verbs moods array
1021 function get_mood_verbs() {
1024 'happy' => t('happy'),
1026 'mellow' => t('mellow'),
1027 'tired' => t('tired'),
1028 'perky' => t('perky'),
1029 'angry' => t('angry'),
1030 'stupefied' => t('stupified'),
1031 'puzzled' => t('puzzled'),
1032 'interested' => t('interested'),
1033 'bitter' => t('bitter'),
1034 'cheerful' => t('cheerful'),
1035 'alive' => t('alive'),
1036 'annoyed' => t('annoyed'),
1037 'anxious' => t('anxious'),
1038 'cranky' => t('cranky'),
1039 'disturbed' => t('disturbed'),
1040 'frustrated' => t('frustrated'),
1041 'motivated' => t('motivated'),
1042 'relaxed' => t('relaxed'),
1043 'surprised' => t('surprised'),
1046 call_hooks('mood_verbs', $arr);
1052 if(! function_exists('smilies')) {
1054 * Replaces text emoticons with graphical images
1056 * It is expected that this function will be called using HTML text.
1057 * We will escape text between HTML pre and code blocks from being
1060 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
1061 * function from being executed by the prepare_text() routine when preparing
1062 * bbcode source for HTML display
1065 * @param boolean $sample
1067 * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1069 function smilies($s, $sample = false) {
1072 if(intval(get_config('system','no_smilies'))
1073 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1076 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1077 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1118 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1119 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1120 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1121 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1122 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1123 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1124 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1125 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1126 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1127 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1128 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1129 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1130 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1131 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1132 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1133 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
1134 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\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-Oo.gif" alt="o_O" />',
1138 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1139 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1140 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1141 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1142 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1143 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1144 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1145 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1146 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1147 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1148 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1149 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1150 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
1151 '<a href="http://redmatrix.me/">red <img class="smiley" src="' . $a->get_baseurl() . '/images/rhash-16.png" alt="red" /></a>'
1154 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1155 call_hooks('smilie', $params);
1158 $s = '<div class="smiley-sample">';
1159 for($x = 0; $x < count($params['texts']); $x ++) {
1160 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1164 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
1165 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1168 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1169 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1175 function smile_encode($m) {
1176 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1179 function smile_decode($m) {
1180 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1185 * expand <3333 to the correct number of hearts
1190 function preg_heart($x) {
1192 if(strlen($x[1]) == 1)
1195 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1196 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1197 $r = str_replace($x[0],$t,$x[0]);
1202 if(! function_exists('day_translate')) {
1204 * Translate days and months names
1209 function day_translate($s) {
1210 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1211 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1214 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1215 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')),
1222 if(! function_exists('normalise_link')) {
1226 * @param string $url
1229 function normalise_link($url) {
1230 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1231 return(rtrim($ret,'/'));
1236 if(! function_exists('link_compare')) {
1238 * Compare two URLs to see if they are the same, but ignore
1239 * slight but hopefully insignificant differences such as if one
1240 * is https and the other isn't, or if one is www.something and
1241 * the other isn't - and also ignore case differences.
1243 * @param string $a first url
1244 * @param string $b second url
1245 * @return boolean True if the URLs match, otherwise False
1248 function link_compare($a,$b) {
1249 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1255 if(! function_exists('redir_private_images')) {
1257 * Find any non-embedded images in private items and add redir links to them
1260 * @param array $item
1262 function redir_private_images($a, &$item) {
1265 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1267 //logger("redir_private_images: matches = " . print_r($matches, true));
1268 foreach($matches as $mtch) {
1269 if(strpos($mtch[1], '/redir') !== false)
1272 if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1273 //logger("redir_private_images: redir");
1274 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1275 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1283 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1284 // If attach is true, also add icons for item attachments
1286 if(! function_exists('prepare_body')) {
1288 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1289 * If attach is true, also add icons for item attachments
1291 * @param array $item
1292 * @param boolean $attach
1293 * @return string item body html
1294 * @hook prepare_body_init item array before any work
1295 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1296 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1298 function prepare_body(&$item,$attach = false, $preview = false) {
1301 call_hooks('prepare_body_init', $item);
1303 $searchpath = $a->get_baseurl()."/search?tag=";
1306 $hashtags = array();
1307 $mentions = array();
1309 if (!get_config('system','suppress_tags')) {
1310 $taglist = q("SELECT `type`, `term`, `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d) ORDER BY `tid`",
1311 intval(TERM_OBJ_POST), intval($item['id']), intval(TERM_HASHTAG), intval(TERM_MENTION));
1313 foreach($taglist as $tag) {
1315 if ($tag["url"] == "")
1316 $tag["url"] = $searchpath.strtolower($tag["term"]);
1318 if ($tag["type"] == TERM_HASHTAG) {
1319 $hashtags[] = "#<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1321 } elseif ($tag["type"] == TERM_MENTION) {
1322 $mentions[] = "@<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1325 $tags[] = $prefix."<a href=\"".$tag["url"]."\" target=\"_blank\">".$tag["term"]."</a>";
1329 $item['tags'] = $tags;
1330 $item['hashtags'] = $hashtags;
1331 $item['mentions'] = $mentions;
1334 $cachefile = get_cachefile(urlencode($item["guid"])."-".hash("md5", $item['body']));
1336 if (($cachefile != '')) {
1337 if (file_exists($cachefile)) {
1338 $stamp1 = microtime(true);
1339 $s = file_get_contents($cachefile);
1340 $a->save_timestamp($stamp1, "file");
1342 redir_private_images($a, $item);
1343 $s = prepare_text($item['body']);
1345 $stamp1 = microtime(true);
1346 file_put_contents($cachefile, $s);
1347 $a->save_timestamp($stamp1, "file");
1349 logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
1352 redir_private_images($a, $item);
1353 $s = prepare_text($item['body']);
1356 require_once("mod/proxy.php");
1357 $s = proxy_parse_html($s);
1359 $prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
1360 call_hooks('prepare_body', $prep_arr);
1361 $s = $prep_arr['html'];
1364 // Replace the blockquotes with quotes that are used in mails
1365 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1366 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1372 $arr = explode('[/attach],',$item['attach']);
1374 $as .= '<div class="body-attach">';
1375 foreach($arr as $r) {
1378 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1380 foreach($matches as $mtch) {
1383 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1384 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1386 $the_url = $mtch[1];
1388 if(strpos($mime, 'video') !== false) {
1391 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1392 '$baseurl' => $a->get_baseurl(),
1394 $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1395 '$baseurl' => $a->get_baseurl(),
1399 $id = end(explode('/', $the_url));
1400 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1403 'title' => t('View Video'),
1410 $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1412 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1413 $filesubtype = str_replace('.', '-', $filesubtype);
1417 $filesubtype = 'unkn';
1420 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1421 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1427 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1430 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1434 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1435 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1437 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1441 $as .= '<div class="clear"></div></div>';
1447 $spoilersearch = '<blockquote class="spoiler">';
1449 // Remove line breaks before the spoiler
1450 while ((strpos($s, "\n".$spoilersearch) !== false))
1451 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1452 while ((strpos($s, "<br />".$spoilersearch) !== false))
1453 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1455 while ((strpos($s, $spoilersearch) !== false)) {
1457 $pos = strpos($s, $spoilersearch);
1458 $rnd = random_string(8);
1459 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1460 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1461 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1464 // Look for quote with author
1465 $authorsearch = '<blockquote class="author">';
1467 while ((strpos($s, $authorsearch) !== false)) {
1469 $pos = strpos($s, $authorsearch);
1470 $rnd = random_string(8);
1471 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1472 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1473 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1476 // replace friendica image url size with theme preference
1477 if (x($a->theme_info,'item_image_size')){
1478 $ps = $a->theme_info['item_image_size'];
1480 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|',"$1-".$ps, $s);
1483 $prep_arr = array('item' => $item, 'html' => $s);
1484 call_hooks('prepare_body_final', $prep_arr);
1486 return $prep_arr['html'];
1490 if(! function_exists('prepare_text')) {
1492 * Given a text string, convert from bbcode to html and add smilie icons.
1494 * @param string $text
1497 function prepare_text($text) {
1499 require_once('include/bbcode.php');
1501 if(stristr($text,'[nosmile]'))
1504 $s = smilies(bbcode($text));
1512 * return array with details for categories and folders for an item
1514 * @param array $item
1518 * [ // categories array
1520 * 'name': 'category name',
1521 * 'removeurl': 'url to remove this category',
1522 * 'first': 'is the first in this array? true/false',
1523 * 'last': 'is the last in this array? true/false',
1529 * 'name': 'folder name',
1530 * 'removeurl': 'url to remove this folder',
1531 * 'first': 'is the first in this array? true/false',
1532 * 'last': 'is the last in this array? true/false',
1538 function get_cats_and_terms($item) {
1541 $categories = array();
1544 $matches = false; $first = true;
1545 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1547 foreach($matches as $mtch) {
1548 $categories[] = array(
1549 'name' => xmlify(file_tag_decode($mtch[1])),
1551 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1558 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1561 if(local_user() == $item['uid']) {
1562 $matches = false; $first = true;
1563 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1565 foreach($matches as $mtch) {
1567 'name' => xmlify(file_tag_decode($mtch[1])),
1569 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1578 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1580 return array($categories, $folders);
1585 if(! function_exists('feed_hublinks')) {
1587 * return atom link elements for all of our hubs
1588 * @return string hub link xml elements
1590 function feed_hublinks() {
1592 $hub = get_config('system','huburl');
1596 $hubs = explode(',', $hub);
1598 foreach($hubs as $h) {
1602 if ($h === '[internal]')
1603 $h = $a->get_baseurl() . '/pubsubhubbub';
1604 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1612 if(! function_exists('feed_salmonlinks')) {
1614 * return atom link elements for salmon endpoints
1615 * @param string $nick user nickname
1616 * @return string salmon link xml elements
1618 function feed_salmonlinks($nick) {
1622 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1624 // old style links that status.net still needed as of 12/2010
1626 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1627 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1631 if(! function_exists('get_plink')) {
1633 * get private link for item
1634 * @param array $item
1635 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1637 function get_plink($item) {
1640 if ($a->user['nickname'] != "") {
1642 //'href' => $a->get_baseurl()."/display/".$a->user['nickname']."/".$item['id'],
1643 'href' => $a->get_baseurl()."/display/".$item['guid'],
1644 'orig' => $a->get_baseurl()."/display/".$item['guid'],
1645 'title' => t('link to source'),
1648 if (x($item,'plink'))
1649 $ret["href"] = $item['plink'];
1651 } elseif (x($item,'plink') && ($item['private'] != 1))
1653 'href' => $item['plink'],
1654 'orig' => $item['plink'],
1655 'title' => t('link to source'),
1660 //if (x($item,'plink') && ($item['private'] != 1))
1665 if(! function_exists('unamp')) {
1667 * replace html amp entity with amp char
1671 function unamp($s) {
1672 return str_replace('&', '&', $s);
1678 if(! function_exists('lang_selector')) {
1680 * get html for language selector
1681 * @global string $lang
1683 * @template lang_selector.tpl
1685 function lang_selector() {
1688 $langs = glob('view/*/strings.php');
1690 $lang_options = array();
1693 if(is_array($langs) && count($langs)) {
1695 if(! in_array('view/en/strings.php',$langs))
1696 $langs[] = 'view/en/';
1698 foreach($langs as $l) {
1700 $lang_options[""] = t('default');
1704 $ll = substr($ll,0,strrpos($ll,'/'));
1705 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1706 $lang_options[$ll]=$ll;
1710 $tpl = get_markup_template("lang_selector.tpl");
1711 $o = replace_macros($tpl, array(
1712 '$title' => t('Select an alternate language'),
1713 '$langs' => array($lang_options, $selected),
1720 if(! function_exists('return_bytes')) {
1722 * return number of bytes in size (K, M, G)
1723 * @param string $size_str
1726 function return_bytes ($size_str) {
1727 switch (substr ($size_str, -1))
1729 case 'M': case 'm': return (int)$size_str * 1048576;
1730 case 'K': case 'k': return (int)$size_str * 1024;
1731 case 'G': case 'g': return (int)$size_str * 1073741824;
1732 default: return $size_str;
1739 function generate_user_guid() {
1742 $guid = random_string(16);
1743 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1748 } while ($found == true );
1755 * @param boolean $strip_padding
1758 function base64url_encode($s, $strip_padding = false) {
1760 $s = strtr(base64_encode($s),'+/','-_');
1763 $s = str_replace('=','',$s);
1772 function base64url_decode($s) {
1775 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1780 * // Placeholder for new rev of salmon which strips base64 padding.
1781 * // PHP base64_decode handles the un-padded input without requiring this step
1782 * // Uncomment if you find you need it.
1785 * if(! strpos($s,'=')) {
1795 return base64_decode(strtr($s,'-_','+/'));
1799 if (!function_exists('str_getcsv')) {
1803 * @param string $input
1804 * @param string $delimiter
1805 * @param string $enclosure
1806 * @param string $escape
1807 * @param string $eol
1808 * @return boolean|array False on error, otherwise array[row][column]
1810 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1811 if (is_string($input) && !empty($input)) {
1813 $tmp = preg_split("/".$eol."/",$input);
1814 if (is_array($tmp) && !empty($tmp)) {
1815 while (list($line_num, $line) = each($tmp)) {
1816 if (preg_match("/".$escape.$enclosure."/",$line)) {
1817 while ($strlen = strlen($line)) {
1818 $pos_delimiter = strpos($line,$delimiter);
1819 $pos_enclosure_start = strpos($line,$enclosure);
1821 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1822 && ($pos_enclosure_start < $pos_delimiter)
1824 $enclosed_str = substr($line,1);
1825 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1826 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1827 $output[$line_num][] = $enclosed_str;
1828 $offset = $pos_enclosure_end+3;
1830 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1831 $output[$line_num][] = substr($line,0);
1832 $offset = strlen($line);
1834 $output[$line_num][] = substr($line,0,$pos_delimiter);
1836 !empty($pos_enclosure_start)
1837 && ($pos_enclosure_start < $pos_delimiter)
1839 ?$pos_enclosure_start
1843 $line = substr($line,$offset);
1846 $line = preg_split("/".$delimiter."/",$line);
1849 * Validating against pesky extra line breaks creating false rows.
1851 if (is_array($line) && !empty($line[0])) {
1852 $output[$line_num] = $line;
1867 * return div element with class 'clear'
1871 function cleardiv() {
1872 return '<div class="clear"></div>';
1876 function bb_translate_video($s) {
1879 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1881 foreach($matches as $mtch) {
1882 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1883 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1884 elseif(stristr($mtch[1],'vimeo'))
1885 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1891 function html2bb_video($s) {
1893 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1894 '[youtube]$2[/youtube]', $s);
1896 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1897 '[youtube]$2[/youtube]', $s);
1899 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1900 '[vimeo]$2[/vimeo]', $s);
1906 * apply xmlify() to all values of array $val, recursively
1910 function array_xmlify($val){
1911 if (is_bool($val)) return $val?"true":"false";
1912 if (is_array($val)) return array_map('array_xmlify', $val);
1913 return xmlify((string) $val);
1918 * transorm link href and img src from relative to absolute
1920 * @param string $text
1921 * @param string $base base url
1924 function reltoabs($text, $base)
1929 $base = rtrim($base,'/');
1931 $base2 = $base . "/";
1934 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1935 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1936 $text = preg_replace($pattern, $replace, $text);
1938 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1939 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1940 $text = preg_replace($pattern, $replace, $text);
1943 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1944 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1945 $text = preg_replace($pattern, $replace, $text);
1947 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1948 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1949 $text = preg_replace($pattern, $replace, $text);
1957 * get translated item type
1959 * @param array $itme
1962 function item_post_type($item) {
1963 if(intval($item['event-id']))
1965 if(strlen($item['resource-id']))
1967 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1968 return t('activity');
1969 if($item['id'] != $item['parent'])
1970 return t('comment');
1974 // post categories and "save to file" use the same item.file table for storage.
1975 // We will differentiate the different uses by wrapping categories in angle brackets
1976 // and save to file categories in square brackets.
1977 // To do this we need to escape these characters if they appear in our tag.
1979 function file_tag_encode($s) {
1980 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1983 function file_tag_decode($s) {
1984 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1987 function file_tag_file_query($table,$s,$type = 'file') {
1990 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1992 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1993 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1996 // ex. given music,video return <music><video> or [music][video]
1997 function file_tag_list_to_file($list,$type = 'file') {
2000 $list_array = explode(",",$list);
2001 if($type == 'file') {
2010 foreach($list_array as $item) {
2012 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
2019 // ex. given <music><video>[friends], return music,video or friends
2020 function file_tag_file_to_list($file,$type = 'file') {
2023 if($type == 'file') {
2024 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
2027 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
2030 foreach($matches as $mtch) {
2033 $list .= file_tag_decode($mtch[1]);
2040 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
2041 // $file_old - categories previously associated with an item
2042 // $file_new - new list of categories for an item
2047 if($file_old == $file_new)
2050 $saved = get_pconfig($uid,'system','filetags');
2051 if(strlen($saved)) {
2052 if($type == 'file') {
2055 $termtype = TERM_FILE;
2060 $termtype = TERM_CATEGORY;
2063 $filetags_updated = $saved;
2065 // check for new tags to be added as filetags in pconfig
2066 $new_tags = array();
2067 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
2069 foreach($check_new_tags as $tag) {
2070 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
2074 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
2076 // check for deleted tags to be removed from filetags in pconfig
2077 $deleted_tags = array();
2078 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
2080 foreach($check_deleted_tags as $tag) {
2081 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
2082 $deleted_tags[] = $tag;
2085 foreach($deleted_tags as $key => $tag) {
2086 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2088 intval(TERM_OBJ_POST),
2092 //$r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
2097 unset($deleted_tags[$key]);
2100 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
2104 if($saved != $filetags_updated) {
2105 set_pconfig($uid,'system','filetags', $filetags_updated);
2110 if(strlen($file_new)) {
2111 set_pconfig($uid,'system','filetags', $file_new);
2116 function file_tag_save_file($uid,$item,$file) {
2117 require_once("include/files.php");
2122 $r = q("select file from item where id = %d and uid = %d limit 1",
2127 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2128 q("update item set file = '%s' where id = %d and uid = %d",
2129 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2134 create_files_from_item($item);
2136 $saved = get_pconfig($uid,'system','filetags');
2137 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2138 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2139 info( t('Item filed') );
2144 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2145 require_once("include/files.php");
2152 $pattern = '<' . file_tag_encode($file) . '>' ;
2153 $termtype = TERM_CATEGORY;
2155 $pattern = '[' . file_tag_encode($file) . ']' ;
2156 $termtype = TERM_FILE;
2160 $r = q("select file from item where id = %d and uid = %d limit 1",
2167 q("update item set file = '%s' where id = %d and uid = %d",
2168 dbesc(str_replace($pattern,'',$r[0]['file'])),
2173 create_files_from_item($item);
2175 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
2177 intval(TERM_OBJ_POST),
2181 //$r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2185 $saved = get_pconfig($uid,'system','filetags');
2186 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2192 function normalise_openid($s) {
2193 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2197 function undo_post_tagging($s) {
2199 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2201 foreach($matches as $mtch) {
2202 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2208 function fix_mce_lf($s) {
2209 $s = str_replace("\r\n","\n",$s);
2210 // $s = str_replace("\n\n","\n",$s);
2215 function protect_sprintf($s) {
2216 return(str_replace('%','%%',$s));
2220 function is_a_date_arg($s) {
2224 if($i <= $y+1 && strpos($s,'-') == 4) {
2225 $m = intval(substr($s,5));
2226 if($m > 0 && $m <= 12)
2234 * remove intentation from a text
2236 function deindent($text, $chr="[\t ]", $count=NULL) {
2237 $text = fix_mce_lf($text);
2238 $lines = explode("\n", $text);
2239 if (is_null($count)) {
2241 $k=0; while($k<count($lines) && strlen($lines[$k])==0) $k++;
2242 preg_match("|^".$chr."*|", $lines[$k], $m);
2243 $count = strlen($m[0]);
2245 for ($k=0; $k<count($lines); $k++){
2246 $lines[$k] = preg_replace("|^".$chr."{".$count."}|", "", $lines[$k]);
2249 return implode("\n", $lines);