3 // This is our template processor.
4 // $s is the string requiring macro substitution.
5 // $r is an array of key value pairs (search => replace)
6 // returns substituted string.
7 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
8 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
9 // depending on the order in which they were declared in the array.
11 require_once("include/template_processor.php");
12 require_once("include/friendica_smarty.php");
14 if(! function_exists('replace_macros')) {
16 * This is our template processor
18 * @param string|FriendicaSmarty $s the string requiring macro substitution,
19 * or an instance of FriendicaSmarty
20 * @param array $r key value pairs (search => replace)
21 * @return string substituted string
23 function replace_macros($s,$r) {
25 $stamp1 = microtime(true);
29 $t = $a->template_engine();
30 $output = $t->replace_macros($s,$r);
32 $a->save_timestamp($stamp1, "rendering");
38 // random string, there are 86 characters max in text mode, 128 for hex
41 define('RANDOM_STRING_HEX', 0x00 );
42 define('RANDOM_STRING_TEXT', 0x01 );
44 if(! function_exists('random_string')) {
45 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
46 // generate a bit of entropy and run it through the whirlpool
47 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
48 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
49 return(substr($s,0,$size));
52 if(! function_exists('notags')) {
54 * This is our primary input filter.
56 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
57 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
58 * after cleansing, and angle chars with the high bit set could get through as markup.
60 * This is now disabled because it was interfering with some legitimate unicode sequences
61 * and hopefully there aren't a lot of those browsers left.
63 * Use this on any text input where angle chars are not valid or permitted
64 * They will be replaced with safer brackets. This may be filtered further
65 * if these are not allowed either.
67 * @param string $string Input string
68 * @return string Filtered string
70 function notags($string) {
72 return(str_replace(array("<",">"), array('[',']'), $string));
74 // High-bit filter no longer used
75 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
80 if(! function_exists('escape_tags')) {
82 * use this on "body" or "content" input where angle chars shouldn't be removed,
83 * and allow them to be safely displayed.
84 * @param string $string
87 function escape_tags($string) {
89 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
93 // generate a string that's random, but usually pronounceable.
94 // used to generate initial passwords
96 if(! function_exists('autoname')) {
98 * generate a string that's random, but usually pronounceable.
99 * used to generate initial passwords
103 function autoname($len) {
108 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
109 if(mt_rand(0,5) == 4)
127 's','sc','sh','sm','sp','st',
135 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
136 'nd','ng','nk','nt','rn','rp','rt');
138 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
139 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
141 $start = mt_rand(0,2);
149 for ($x = 0; $x < $len; $x ++) {
150 $r = mt_rand(0,count($table) - 1);
153 if($table == $vowels)
154 $table = array_merge($cons,$midcons);
160 $word = substr($word,0,$len);
162 foreach($noend as $noe) {
163 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
164 $word = substr($word,0,-1);
168 if(substr($word,-1) == 'q')
169 $word = substr($word,0,-1);
174 // escape text ($str) for XML transport
175 // returns escaped text.
177 if(! function_exists('xmlify')) {
179 * escape text ($str) for XML transport
181 * @return string Escaped text.
183 function xmlify($str) {
186 $len = mb_strlen($str);
187 for($x = 0; $x < $len; $x ++) {
188 $char = mb_substr($str,$x,1);
218 $buffer = mb_ereg_replace("&", "&", $str);
219 $buffer = mb_ereg_replace("'", "'", $buffer);
220 $buffer = mb_ereg_replace("\"", """, $buffer);
221 $buffer = mb_ereg_replace("<", "<", $buffer);
222 $buffer = mb_ereg_replace(">", ">", $buffer);
224 $buffer = trim($buffer);
228 if(! function_exists('unxmlify')) {
231 * @param string $s xml escaped text
232 * @return string unescaped text
234 function unxmlify($s) {
235 // $ret = str_replace('&','&', $s);
236 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
237 $ret = mb_ereg_replace('&', '&', $s);
238 $ret = mb_ereg_replace(''', "'", $ret);
239 $ret = mb_ereg_replace('"', '"', $ret);
240 $ret = mb_ereg_replace('<', "<", $ret);
241 $ret = mb_ereg_replace('>', ">", $ret);
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')) {
265 * Automatic pagination.
267 * To use, get the count of total items.
268 * Then call $a->set_pager_total($number_items);
269 * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
270 * Then call paginate($a) after the end of the display loop to insert the pager block on the page
271 * (assuming there are enough items to paginate).
272 * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
273 * will limit the results to the correct items for the current page.
274 * The actual page handling is then accomplished at the application layer.
276 * @param App $a App instance
277 * @return string html for pagination #FIXME remove html
279 function paginate(&$a) {
281 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
283 // $stripped = preg_replace('/&zrl=(.*?)([\?&]|$)/ism','',$stripped);
285 $stripped = str_replace('q=','',$stripped);
286 $stripped = trim($stripped,'/');
287 $pagenum = $a->pager['page'];
288 $url = $a->get_baseurl() . '/' . $stripped;
291 if($a->pager['total'] > $a->pager['itemspage']) {
292 $o .= '<div class="pager">';
293 if($a->pager['page'] != 1)
294 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
296 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
298 $numpages = $a->pager['total'] / $a->pager['itemspage'];
301 $numstop = $numpages;
304 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
305 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
308 for($i = $numstart; $i <= $numstop; $i++){
309 if($i == $a->pager['page'])
310 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
312 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
316 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
317 if($i == $a->pager['page'])
318 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
320 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
324 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
325 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
327 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
328 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
329 $o .= '</div>'."\r\n";
334 if(! function_exists('alt_pager')) {
337 * @param App $a App instance
339 * @return string html for pagination #FIXME remove html
341 function alt_pager(&$a, $i) {
343 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
344 $stripped = str_replace('q=','',$stripped);
345 $stripped = trim($stripped,'/');
346 $pagenum = $a->pager['page'];
347 $url = $a->get_baseurl() . '/' . $stripped;
349 $o .= '<div class="pager">';
351 if($a->pager['page']>1)
352 $o .= "<a href=\"$url"."&page=".($a->pager['page'] - 1).'" class="pager_newer">' . t('newer') . '</a>';
354 if($a->pager['page']>1)
355 $o .= " - ";
356 $o .= "<a href=\"$url"."&page=".($a->pager['page'] + 1).'" class="pager_older">' . t('older') . '</a>';
360 $o .= '</div>'."\r\n";
366 if(! function_exists('expand_acl')) {
368 * Turn user/group ACLs stored as angle bracketed text into arrays
373 function expand_acl($s) {
374 // turn string array of angle-bracketed elements into numeric array
375 // e.g. "<1><2><3>" => array(1,2,3);
379 $t = str_replace('<','',$s);
380 $a = explode('>',$t);
383 $ret[] = intval($aa);
389 if(! function_exists('sanitise_acl')) {
391 * Wrap ACL elements in angle brackets for storage
392 * @param string $item
394 function sanitise_acl(&$item) {
396 $item = '<' . intval(notags(trim($item))) . '>';
402 if(! function_exists('perms2str')) {
404 * Convert an ACL array to a storable string
406 * Normally ACL permissions will be an array.
407 * We'll also allow a comma-separated string.
409 * @param string|array $p
412 function perms2str($p) {
417 $tmp = explode(',',$p);
420 array_walk($tmp,'sanitise_acl');
421 $ret = implode('',$tmp);
427 if(! function_exists('item_new_uri')) {
429 * generate a guaranteed unique (for this domain) item ID for ATOM
430 * safe from birthday paradox
432 * @param string $hostname
436 function item_new_uri($hostname,$uid) {
440 $hash = random_string();
442 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
444 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
448 } while($dups == true);
452 // Generate a guaranteed unique photo ID.
453 // safe from birthday paradox
455 if(! function_exists('photo_new_resource')) {
457 * Generate a guaranteed unique photo ID.
458 * safe from birthday paradox
462 function photo_new_resource() {
466 $resource = hash('md5',uniqid(mt_rand(),true));
467 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
472 } while($found == true);
477 if(! function_exists('load_view_file')) {
480 * wrapper to load a view template, checking for alternate
481 * languages before falling back to the default
483 * @global string $lang
485 * @param string $s view name
488 function load_view_file($s) {
494 if(file_exists("$d/$lang/$b")) {
495 $stamp1 = microtime(true);
496 $content = file_get_contents("$d/$lang/$b");
497 $a->save_timestamp($stamp1, "file");
501 $theme = current_theme();
503 if(file_exists("$d/theme/$theme/$b")) {
504 $stamp1 = microtime(true);
505 $content = file_get_contents("$d/theme/$theme/$b");
506 $a->save_timestamp($stamp1, "file");
510 $stamp1 = microtime(true);
511 $content = file_get_contents($s);
512 $a->save_timestamp($stamp1, "file");
516 if(! function_exists('get_intltext_template')) {
518 * load a view template, checking for alternate
519 * languages before falling back to the default
521 * @global string $lang
522 * @param string $s view path
525 function get_intltext_template($s) {
530 if($a->theme['template_engine'] === 'smarty3')
531 $engine = "/smarty3";
536 if(file_exists("view/$lang$engine/$s")) {
537 $stamp1 = microtime(true);
538 $content = file_get_contents("view/$lang$engine/$s");
539 $a->save_timestamp($stamp1, "file");
541 } elseif(file_exists("view/en$engine/$s")) {
542 $stamp1 = microtime(true);
543 $content = file_get_contents("view/en$engine/$s");
544 $a->save_timestamp($stamp1, "file");
547 $stamp1 = microtime(true);
548 $content = file_get_contents("view$engine/$s");
549 $a->save_timestamp($stamp1, "file");
554 if(! function_exists('get_markup_template')) {
559 * @param string $root
562 function get_markup_template($s, $root = '') {
563 $stamp1 = microtime(true);
566 $t = $a->template_engine();
568 $template = $t->get_template_file($s, $root);
570 $a->save_timestamp($stamp1, "file");
575 if(! function_exists("get_template_file")) {
579 * @param string $filename
580 * @param string $root
583 function get_template_file($a, $filename, $root = '') {
584 $theme = current_theme();
586 // Make sure $root ends with a slash /
587 if($root !== '' && $root[strlen($root)-1] !== '/')
590 if(file_exists("{$root}view/theme/$theme/$filename"))
591 $template_file = "{$root}view/theme/$theme/$filename";
592 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
593 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
594 elseif (file_exists("{$root}/$filename"))
595 $template_file = "{$root}/$filename";
597 $template_file = "{$root}view/$filename";
599 return $template_file;
608 if(! function_exists('attribute_contains')) {
610 * for html,xml parsing - let's say you've got
611 * an attribute foobar="class1 class2 class3"
612 * and you want to find out if it contains 'class3'.
613 * you can't use a normal sub string search because you
614 * might match 'notclass3' and a regex to do the job is
615 * possible but a bit complicated.
616 * pass the attribute string as $attr and the attribute you
617 * are looking for as $s - returns true if found, otherwise false
619 * @param string $attr attribute value
620 * @param string $s string to search
621 * @return boolean True if found, False otherwise
623 function attribute_contains($attr,$s) {
624 $a = explode(' ', $attr);
625 if(count($a) && in_array($s,$a))
630 if(! function_exists('logger')) {
633 * LOGGER_NORMAL (default)
644 function logger($msg,$level = 0) {
645 // turn off logger in install mode
649 if(($a->module == 'install') || (! ($db && $db->connected))) return;
651 $debugging = get_config('system','debugging');
652 $loglevel = intval(get_config('system','loglevel'));
653 $logfile = get_config('system','logfile');
655 if((! $debugging) || (! $logfile) || ($level > $loglevel))
658 $stamp1 = microtime(true);
659 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
660 $a->save_timestamp($stamp1, "file");
665 if(! function_exists('activity_match')) {
667 * Compare activity uri. Knows about activity namespace.
669 * @param string $haystack
670 * @param string $needle
673 function activity_match($haystack,$needle) {
674 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
680 if(! function_exists('get_tags')) {
682 * Pull out all #hashtags and @person tags from $s;
683 * We also get @person@domain.com - which would make
684 * the regex quite complicated as tags can also
685 * end a sentence. So we'll run through our results
686 * and strip the period from any tags which end with one.
687 * Returns array of tags found, or empty array.
692 function get_tags($s) {
695 // ignore anything in a code block
696 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
698 // Force line feeds at bbtags
699 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
701 // ignore anything in a bbtag
702 $s = preg_replace('/\[(.*?)\]/sm','',$s);
704 // Match full names against @tags including the space between first and last
705 // We will look these up afterward to see if they are full names or not recognisable.
707 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
708 foreach($match[1] as $mtch) {
709 if(strstr($mtch,"]")) {
710 // we might be inside a bbcode color tag - leave it alone
713 if(substr($mtch,-1,1) === '.')
714 $ret[] = substr($mtch,0,-1);
720 // Otherwise pull out single word tags. These can be @nickname, @first_last
723 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
724 foreach($match[1] as $mtch) {
725 if(strstr($mtch,"]")) {
726 // we might be inside a bbcode color tag - leave it alone
729 if(substr($mtch,-1,1) === '.')
730 $mtch = substr($mtch,0,-1);
731 // ignore strictly numeric tags like #1
732 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
734 // try not to catch url fragments
735 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
746 if(! function_exists('qp')) {
748 * quick and dirty quoted_printable encoding
754 return str_replace ("%","=",rawurlencode($s));
759 if(! function_exists('get_mentions')) {
762 * @return string html for mentions #FIXME: remove html
764 function get_mentions($item) {
766 if(! strlen($item['tag']))
769 $arr = explode(',',$item['tag']);
770 foreach($arr as $x) {
772 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
773 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
774 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
780 if(! function_exists('contact_block')) {
782 * Get html for contact block.
784 * @template contact_block.tpl
785 * @hook contact_block_end (contacts=>array, output=>string)
788 function contact_block() {
792 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
798 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
800 $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",
801 intval($a->profile['uid'])
804 $total = intval($r[0]['total']);
807 $contacts = t('No contacts');
811 $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",
812 intval($a->profile['uid']),
816 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
819 $micropro[] = micropro($rr,true,'mpfriend');
824 $tpl = get_markup_template('contact_block.tpl');
825 $o = replace_macros($tpl, array(
826 '$contacts' => $contacts,
827 '$nickname' => $a->profile['nickname'],
828 '$viewcontacts' => t('View Contacts'),
829 '$micropro' => $micropro,
832 $arr = array('contacts' => $r, 'output' => $o);
834 call_hooks('contact_block_end', $arr);
839 if(! function_exists('micropro')) {
842 * @param array $contact
843 * @param boolean $redirect
844 * @param string $class
845 * @param boolean $textmode
846 * @return string #FIXME: remove html
848 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
851 $class = ' ' . $class;
853 $url = $contact['url'];
859 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
860 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
862 $url = $redirect_url;
863 $sparkle = ' sparkle';
868 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
872 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
873 . (($click) ? ' fakelink' : '') . '" '
874 . (($redir) ? ' target="redir" ' : '')
875 . (($url) ? ' href="' . $url . '"' : '') . $click
876 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
877 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
880 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
881 . (($click) ? ' fakelink' : '') . '" '
882 . (($redir) ? ' target="redir" ' : '')
883 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
884 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
885 . '" /></a></div>' . "\r\n";
891 if(! function_exists('search')) {
895 * @param string $s search query
896 * @param string $id html id
897 * @param string $url search url
898 * @param boolean $save show save search button
899 * @return string html for search box #FIXME: remove html
901 function search($s,$id='search-box',$url='/search',$save = false) {
903 $o = '<div id="' . $id . '">';
904 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
905 $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
906 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
908 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
909 $o .= '</form></div>';
913 if(! function_exists('valid_email')) {
915 * Check if $x is a valid email string
920 function valid_email($x){
922 if(get_config('system','disable_email_validation'))
925 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
931 if(! function_exists('linkify')) {
933 * Replace naked text hyperlink with HTML formatted hyperlink
937 function linkify($s) {
938 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
939 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
947 * @return array index is present tense verb
948 value is array containing past tense verb, translation of present, translation of past
949 * @hook poke_verbs pokes array
951 function get_poke_verbs() {
953 // index is present tense verb
954 // value is array containing past tense verb, translation of present, translation of past
957 'poke' => array( 'poked', t('poke'), t('poked')),
958 'ping' => array( 'pinged', t('ping'), t('pinged')),
959 'prod' => array( 'prodded', t('prod'), t('prodded')),
960 'slap' => array( 'slapped', t('slap'), t('slapped')),
961 'finger' => array( 'fingered', t('finger'), t('fingered')),
962 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
964 call_hooks('poke_verbs', $arr);
970 * @return array index is mood, value is translated mood
971 * @hook mood_verbs moods array
973 function get_mood_verbs() {
976 'happy' => t('happy'),
978 'mellow' => t('mellow'),
979 'tired' => t('tired'),
980 'perky' => t('perky'),
981 'angry' => t('angry'),
982 'stupefied' => t('stupified'),
983 'puzzled' => t('puzzled'),
984 'interested' => t('interested'),
985 'bitter' => t('bitter'),
986 'cheerful' => t('cheerful'),
987 'alive' => t('alive'),
988 'annoyed' => t('annoyed'),
989 'anxious' => t('anxious'),
990 'cranky' => t('cranky'),
991 'disturbed' => t('disturbed'),
992 'frustrated' => t('frustrated'),
993 'motivated' => t('motivated'),
994 'relaxed' => t('relaxed'),
995 'surprised' => t('surprised'),
998 call_hooks('mood_verbs', $arr);
1004 if(! function_exists('smilies')) {
1006 * Replaces text emoticons with graphical images
1008 * It is expected that this function will be called using HTML text.
1009 * We will escape text between HTML pre and code blocks from being
1012 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
1013 * function from being executed by the prepare_text() routine when preparing
1014 * bbcode source for HTML display
1017 * @param boolean $sample
1019 * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1021 function smilies($s, $sample = false) {
1024 if(intval(get_config('system','no_smilies'))
1025 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1028 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1029 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1069 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1070 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1071 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1072 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1073 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1074 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1075 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1076 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1077 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1078 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1079 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1080 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1081 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1082 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1083 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1084 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
1085 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
1086 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
1087 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
1088 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
1089 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1090 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1091 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1092 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1093 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1094 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1095 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1096 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1097 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1098 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1099 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1100 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1101 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
1104 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1105 call_hooks('smilie', $params);
1108 $s = '<div class="smiley-sample">';
1109 for($x = 0; $x < count($params['texts']); $x ++) {
1110 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1114 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
1115 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1118 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1119 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1125 function smile_encode($m) {
1126 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1129 function smile_decode($m) {
1130 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1135 * expand <3333 to the correct number of hearts
1140 function preg_heart($x) {
1142 if(strlen($x[1]) == 1)
1145 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1146 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1147 $r = str_replace($x[0],$t,$x[0]);
1152 if(! function_exists('day_translate')) {
1154 * Translate days and months names
1159 function day_translate($s) {
1160 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1161 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1164 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1165 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')),
1172 if(! function_exists('normalise_link')) {
1176 * @param string $url
1179 function normalise_link($url) {
1180 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1181 return(rtrim($ret,'/'));
1186 if(! function_exists('link_compare')) {
1188 * Compare two URLs to see if they are the same, but ignore
1189 * slight but hopefully insignificant differences such as if one
1190 * is https and the other isn't, or if one is www.something and
1191 * the other isn't - and also ignore case differences.
1193 * @param string $a first url
1194 * @param string $b second url
1195 * @return boolean True if the URLs match, otherwise False
1198 function link_compare($a,$b) {
1199 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1205 if(! function_exists('redir_private_images')) {
1207 * Find any non-embedded images in private items and add redir links to them
1210 * @param array $item
1212 function redir_private_images($a, &$item) {
1215 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1217 //logger("redir_private_images: matches = " . print_r($matches, true));
1218 foreach($matches as $mtch) {
1219 if(strpos($mtch[1], '/redir') !== false)
1222 if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1223 //logger("redir_private_images: redir");
1224 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1225 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1233 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1234 // If attach is true, also add icons for item attachments
1236 if(! function_exists('prepare_body')) {
1238 * Given an item array, convert the body element from bbcode to html and add smilie icons.
1239 * If attach is true, also add icons for item attachments
1241 * @param array $item
1242 * @param boolean $attach
1243 * @return string item body html
1244 * @hook prepare_body_init item array before any work
1245 * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1246 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1248 function prepare_body($item,$attach = false) {
1251 call_hooks('prepare_body_init', $item);
1253 //$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
1254 $cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
1256 if (($cachefile != '')) {
1257 if (file_exists($cachefile)) {
1258 $stamp1 = microtime(true);
1259 $s = file_get_contents($cachefile);
1260 $a->save_timestamp($stamp1, "file");
1262 redir_private_images($a, $item);
1263 $s = prepare_text($item['body']);
1265 $stamp1 = microtime(true);
1266 file_put_contents($cachefile, $s);
1267 $a->save_timestamp($stamp1, "file");
1269 logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
1272 redir_private_images($a, $item);
1273 $s = prepare_text($item['body']);
1277 $prep_arr = array('item' => $item, 'html' => $s);
1278 call_hooks('prepare_body', $prep_arr);
1279 $s = $prep_arr['html'];
1282 // Replace the blockquotes with quotes that are used in mails
1283 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1284 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1288 $arr = explode('[/attach],',$item['attach']);
1290 $s .= '<div class="body-attach">';
1291 foreach($arr as $r) {
1294 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1296 foreach($matches as $mtch) {
1297 $filetype = strtolower(substr( $mtch[3], 0, strpos($mtch[3],'/') ));
1299 $filesubtype = strtolower(substr( $mtch[3], strpos($mtch[3],'/') + 1 ));
1300 $filesubtype = str_replace('.', '-', $filesubtype);
1304 $filesubtype = 'unkn';
1307 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1308 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1314 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1317 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1321 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1322 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1323 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1324 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1326 $the_url = $mtch[1];
1328 $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
1332 $s .= '<div class="clear"></div></div>';
1337 $spoilersearch = '<blockquote class="spoiler">';
1339 // Remove line breaks before the spoiler
1340 while ((strpos($s, "\n".$spoilersearch) !== false))
1341 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1342 while ((strpos($s, "<br />".$spoilersearch) !== false))
1343 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1345 while ((strpos($s, $spoilersearch) !== false)) {
1347 $pos = strpos($s, $spoilersearch);
1348 $rnd = random_string(8);
1349 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1350 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1351 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1354 // Look for quote with author
1355 $authorsearch = '<blockquote class="author">';
1357 while ((strpos($s, $authorsearch) !== false)) {
1359 $pos = strpos($s, $authorsearch);
1360 $rnd = random_string(8);
1361 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1362 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1363 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1366 $prep_arr = array('item' => $item, 'html' => $s);
1367 call_hooks('prepare_body_final', $prep_arr);
1369 return $prep_arr['html'];
1373 if(! function_exists('prepare_text')) {
1375 * Given a text string, convert from bbcode to html and add smilie icons.
1377 * @param string $text
1380 function prepare_text($text) {
1382 require_once('include/bbcode.php');
1384 if(stristr($text,'[nosmile]'))
1387 $s = smilies(bbcode($text));
1395 * return array with details for categories and folders for an item
1397 * @param array $item
1401 * [ // categories array
1403 * 'name': 'category name',
1404 * 'removeurl': 'url to remove this category',
1405 * 'first': 'is the first in this array? true/false',
1406 * 'last': 'is the last in this array? true/false',
1412 * 'name': 'folder name',
1413 * 'removeurl': 'url to remove this folder',
1414 * 'first': 'is the first in this array? true/false',
1415 * 'last': 'is the last in this array? true/false',
1421 function get_cats_and_terms($item) {
1424 $categories = array();
1427 $matches = false; $first = true;
1428 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1430 foreach($matches as $mtch) {
1431 $categories[] = array(
1432 'name' => xmlify(file_tag_decode($mtch[1])),
1434 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1441 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1444 if(local_user() == $item['uid']) {
1445 $matches = false; $first = true;
1446 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1448 foreach($matches as $mtch) {
1450 'name' => xmlify(file_tag_decode($mtch[1])),
1452 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1461 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1463 return array($categories, $folders);
1468 if(! function_exists('feed_hublinks')) {
1470 * return atom link elements for all of our hubs
1471 * @return string hub link xml elements
1473 function feed_hublinks() {
1475 $hub = get_config('system','huburl');
1479 $hubs = explode(',', $hub);
1481 foreach($hubs as $h) {
1485 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1493 if(! function_exists('feed_salmonlinks')) {
1495 * return atom link elements for salmon endpoints
1496 * @param string $nick user nickname
1497 * @return string salmon link xml elements
1499 function feed_salmonlinks($nick) {
1503 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1505 // old style links that status.net still needed as of 12/2010
1507 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1508 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1512 if(! function_exists('get_plink')) {
1514 * get private link for item
1515 * @param array $item
1516 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1518 function get_plink($item) {
1520 if (x($item,'plink') && ($item['private'] != 1)) {
1522 'href' => $item['plink'],
1523 'title' => t('link to source'),
1531 if(! function_exists('unamp')) {
1533 * replace html amp entity with amp char
1537 function unamp($s) {
1538 return str_replace('&', '&', $s);
1544 if(! function_exists('lang_selector')) {
1546 * get html for language selector
1547 * @global string $lang
1549 * @template lang_selector.tpl
1551 function lang_selector() {
1554 $langs = glob('view/*/strings.php');
1556 $lang_options = array();
1559 if(is_array($langs) && count($langs)) {
1561 if(! in_array('view/en/strings.php',$langs))
1562 $langs[] = 'view/en/';
1564 foreach($langs as $l) {
1566 $lang_options[""] = t('default');
1570 $ll = substr($ll,0,strrpos($ll,'/'));
1571 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1572 $lang_options[$ll]=$ll;
1576 $tpl = get_markup_template("lang_selector.tpl");
1577 $o = replace_macros($tpl, array(
1578 '$title' => t('Select an alternate language'),
1579 '$langs' => array($lang_options, $selected),
1586 if(! function_exists('return_bytes')) {
1588 * return number of bytes in size (K, M, G)
1589 * @param string $size_str
1592 function return_bytes ($size_str) {
1593 switch (substr ($size_str, -1))
1595 case 'M': case 'm': return (int)$size_str * 1048576;
1596 case 'K': case 'k': return (int)$size_str * 1024;
1597 case 'G': case 'g': return (int)$size_str * 1073741824;
1598 default: return $size_str;
1605 function generate_user_guid() {
1608 $guid = random_string(16);
1609 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1614 } while ($found == true );
1621 * @param boolean $strip_padding
1624 function base64url_encode($s, $strip_padding = false) {
1626 $s = strtr(base64_encode($s),'+/','-_');
1629 $s = str_replace('=','',$s);
1638 function base64url_decode($s) {
1641 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1646 * // Placeholder for new rev of salmon which strips base64 padding.
1647 * // PHP base64_decode handles the un-padded input without requiring this step
1648 * // Uncomment if you find you need it.
1651 * if(! strpos($s,'=')) {
1661 return base64_decode(strtr($s,'-_','+/'));
1665 if (!function_exists('str_getcsv')) {
1669 * @param string $input
1670 * @param string $delimiter
1671 * @param string $enclosure
1672 * @param string $escape
1673 * @param string $eol
1674 * @return boolean|array False on error, otherwise array[row][column]
1676 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1677 if (is_string($input) && !empty($input)) {
1679 $tmp = preg_split("/".$eol."/",$input);
1680 if (is_array($tmp) && !empty($tmp)) {
1681 while (list($line_num, $line) = each($tmp)) {
1682 if (preg_match("/".$escape.$enclosure."/",$line)) {
1683 while ($strlen = strlen($line)) {
1684 $pos_delimiter = strpos($line,$delimiter);
1685 $pos_enclosure_start = strpos($line,$enclosure);
1687 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1688 && ($pos_enclosure_start < $pos_delimiter)
1690 $enclosed_str = substr($line,1);
1691 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1692 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1693 $output[$line_num][] = $enclosed_str;
1694 $offset = $pos_enclosure_end+3;
1696 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1697 $output[$line_num][] = substr($line,0);
1698 $offset = strlen($line);
1700 $output[$line_num][] = substr($line,0,$pos_delimiter);
1702 !empty($pos_enclosure_start)
1703 && ($pos_enclosure_start < $pos_delimiter)
1705 ?$pos_enclosure_start
1709 $line = substr($line,$offset);
1712 $line = preg_split("/".$delimiter."/",$line);
1715 * Validating against pesky extra line breaks creating false rows.
1717 if (is_array($line) && !empty($line[0])) {
1718 $output[$line_num] = $line;
1733 * return div element with class 'clear'
1737 function cleardiv() {
1738 return '<div class="clear"></div>';
1742 function bb_translate_video($s) {
1745 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1747 foreach($matches as $mtch) {
1748 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1749 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1750 elseif(stristr($mtch[1],'vimeo'))
1751 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1757 function html2bb_video($s) {
1759 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1760 '[youtube]$2[/youtube]', $s);
1762 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1763 '[youtube]$2[/youtube]', $s);
1765 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1766 '[vimeo]$2[/vimeo]', $s);
1772 * apply xmlify() to all values of array $val, recursively
1776 function array_xmlify($val){
1777 if (is_bool($val)) return $val?"true":"false";
1778 if (is_array($val)) return array_map('array_xmlify', $val);
1779 return xmlify((string) $val);
1784 * transorm link href and img src from relative to absolute
1786 * @param string $text
1787 * @param string $base base url
1790 function reltoabs($text, $base)
1795 $base = rtrim($base,'/');
1797 $base2 = $base . "/";
1800 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1801 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1802 $text = preg_replace($pattern, $replace, $text);
1804 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1805 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1806 $text = preg_replace($pattern, $replace, $text);
1809 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1810 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1811 $text = preg_replace($pattern, $replace, $text);
1813 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1814 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1815 $text = preg_replace($pattern, $replace, $text);
1823 * get translated item type
1825 * @param array $itme
1828 function item_post_type($item) {
1829 if(intval($item['event-id']))
1831 if(strlen($item['resource-id']))
1833 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1834 return t('activity');
1835 if($item['id'] != $item['parent'])
1836 return t('comment');
1840 // post categories and "save to file" use the same item.file table for storage.
1841 // We will differentiate the different uses by wrapping categories in angle brackets
1842 // and save to file categories in square brackets.
1843 // To do this we need to escape these characters if they appear in our tag.
1845 function file_tag_encode($s) {
1846 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1849 function file_tag_decode($s) {
1850 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1853 function file_tag_file_query($table,$s,$type = 'file') {
1856 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1858 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1859 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1862 // ex. given music,video return <music><video> or [music][video]
1863 function file_tag_list_to_file($list,$type = 'file') {
1866 $list_array = explode(",",$list);
1867 if($type == 'file') {
1876 foreach($list_array as $item) {
1878 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1885 // ex. given <music><video>[friends], return music,video or friends
1886 function file_tag_file_to_list($file,$type = 'file') {
1889 if($type == 'file') {
1890 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1893 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1896 foreach($matches as $mtch) {
1899 $list .= file_tag_decode($mtch[1]);
1906 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1907 // $file_old - categories previously associated with an item
1908 // $file_new - new list of categories for an item
1913 if($file_old == $file_new)
1916 $saved = get_pconfig($uid,'system','filetags');
1917 if(strlen($saved)) {
1918 if($type == 'file') {
1927 $filetags_updated = $saved;
1929 // check for new tags to be added as filetags in pconfig
1930 $new_tags = array();
1931 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1933 foreach($check_new_tags as $tag) {
1934 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1938 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1940 // check for deleted tags to be removed from filetags in pconfig
1941 $deleted_tags = array();
1942 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1944 foreach($check_deleted_tags as $tag) {
1945 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1946 $deleted_tags[] = $tag;
1949 foreach($deleted_tags as $key => $tag) {
1950 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1955 unset($deleted_tags[$key]);
1958 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1962 if($saved != $filetags_updated) {
1963 set_pconfig($uid,'system','filetags', $filetags_updated);
1968 if(strlen($file_new)) {
1969 set_pconfig($uid,'system','filetags', $file_new);
1974 function file_tag_save_file($uid,$item,$file) {
1978 $r = q("select file from item where id = %d and uid = %d limit 1",
1983 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1984 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1985 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1989 $saved = get_pconfig($uid,'system','filetags');
1990 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1991 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1992 info( t('Item filed') );
1997 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2003 $pattern = '<' . file_tag_encode($file) . '>' ;
2005 $pattern = '[' . file_tag_encode($file) . ']' ;
2008 $r = q("select file from item where id = %d and uid = %d limit 1",
2015 q("update item set file = '%s' where id = %d and uid = %d limit 1",
2016 dbesc(str_replace($pattern,'',$r[0]['file'])),
2021 $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2026 $saved = get_pconfig($uid,'system','filetags');
2027 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2033 function normalise_openid($s) {
2034 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2038 function undo_post_tagging($s) {
2040 $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2042 foreach($matches as $mtch) {
2043 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2049 function fix_mce_lf($s) {
2050 $s = str_replace("\r\n","\n",$s);
2051 // $s = str_replace("\n\n","\n",$s);
2056 function protect_sprintf($s) {
2057 return(str_replace('%','%%',$s));
2061 function is_a_date_arg($s) {
2065 if($i <= $y+1 && strpos($s,'-') == 4) {
2066 $m = intval(substr($s,5));
2067 if($m > 0 && $m <= 12)