3 * @file include/text.php
7 use Friendica\Content\ContactSelector;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Smilies;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Event;
20 use Friendica\Model\Item;
21 use Friendica\Render\FriendicaSmarty;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Map;
24 use Friendica\Util\Proxy as ProxyUtils;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Renderer;
28 use Friendica\Model\FileTag;
30 require_once "include/conversation.php";
33 * @brief Generates a pseudo-random string of hexadecimal characters
38 function random_string($size = 64)
40 $byte_size = ceil($size / 2);
42 $bytes = random_bytes($byte_size);
44 $return = substr(bin2hex($bytes), 0, $size);
50 * This is our primary input filter.
52 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
53 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
54 * after cleansing, and angle chars with the high bit set could get through as markup.
56 * This is now disabled because it was interfering with some legitimate unicode sequences
57 * and hopefully there aren't a lot of those browsers left.
59 * Use this on any text input where angle chars are not valid or permitted
60 * They will be replaced with safer brackets. This may be filtered further
61 * if these are not allowed either.
63 * @param string $string Input string
64 * @return string Filtered string
66 function notags($string) {
67 return str_replace(["<", ">"], ['[', ']'], $string);
69 // High-bit filter no longer used
70 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
75 * use this on "body" or "content" input where angle chars shouldn't be removed,
76 * and allow them to be safely displayed.
77 * @param string $string
80 function escape_tags($string) {
81 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
86 * generate a string that's random, but usually pronounceable.
87 * used to generate initial passwords
91 function autoname($len) {
97 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
98 if (mt_rand(0, 5) == 4) {
117 's','sc','sh','sm','sp','st',
125 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
126 'nd','ng','nk','nt','rn','rp','rt'];
128 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
129 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh','q'];
131 $start = mt_rand(0,2);
140 for ($x = 0; $x < $len; $x ++) {
141 $r = mt_rand(0,count($table) - 1);
144 if ($table == $vowels) {
145 $table = array_merge($cons,$midcons);
152 $word = substr($word,0,$len);
154 foreach ($noend as $noe) {
155 $noelen = strlen($noe);
156 if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
157 $word = autoname($len);
167 * escape text ($str) for XML transport
169 * @return string Escaped text.
171 function xmlify($str) {
172 /// @TODO deprecated code found?
175 $len = mb_strlen($str);
176 for ($x = 0; $x < $len; $x ++) {
177 $char = mb_substr($str,$x,1);
207 $buffer = mb_ereg_replace("&", "&", $str);
208 $buffer = mb_ereg_replace("'", "'", $buffer);
209 $buffer = mb_ereg_replace('"', """, $buffer);
210 $buffer = mb_ereg_replace("<", "<", $buffer);
211 $buffer = mb_ereg_replace(">", ">", $buffer);
213 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
214 $buffer = trim($buffer);
222 * @param string $s xml escaped text
223 * @return string unescaped text
225 function unxmlify($s) {
226 /// @TODO deprecated code found?
227 // $ret = str_replace('&','&', $s);
228 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
229 /*$ret = mb_ereg_replace('&', '&', $s);
230 $ret = mb_ereg_replace(''', "'", $ret);
231 $ret = mb_ereg_replace('"', '"', $ret);
232 $ret = mb_ereg_replace('<', "<", $ret);
233 $ret = mb_ereg_replace('>', ">", $ret);
235 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
240 * Loader for infinite scrolling
241 * @return string html for loader
243 function scroll_loader() {
244 $tpl = Renderer::getMarkupTemplate("scroll_loader.tpl");
245 return Renderer::replaceMacros($tpl, [
246 'wait' => L10n::t('Loading more entries...'),
247 'end' => L10n::t('The end')
253 * Turn user/group ACLs stored as angle bracketed text into arrays
258 function expand_acl($s) {
259 // turn string array of angle-bracketed elements into numeric array
260 // e.g. "<1><2><3>" => array(1,2,3);
264 $t = str_replace('<', '', $s);
265 $a = explode('>', $t);
266 foreach ($a as $aa) {
268 $ret[] = intval($aa);
277 * Wrap ACL elements in angle brackets for storage
278 * @param string $item
280 function sanitise_acl(&$item) {
282 $item = '<' . intval(notags(trim($item))) . '>';
290 * Convert an ACL array to a storable string
292 * Normally ACL permissions will be an array.
293 * We'll also allow a comma-separated string.
295 * @param string|array $p
298 function perms2str($p) {
303 $tmp = explode(',', $p);
306 if (is_array($tmp)) {
307 array_walk($tmp, 'sanitise_acl');
308 $ret = implode('', $tmp);
314 * for html,xml parsing - let's say you've got
315 * an attribute foobar="class1 class2 class3"
316 * and you want to find out if it contains 'class3'.
317 * you can't use a normal sub string search because you
318 * might match 'notclass3' and a regex to do the job is
319 * possible but a bit complicated.
320 * pass the attribute string as $attr and the attribute you
321 * are looking for as $s - returns true if found, otherwise false
323 * @param string $attr attribute value
324 * @param string $s string to search
325 * @return boolean True if found, False otherwise
327 function attribute_contains($attr, $s) {
328 $a = explode(' ', $attr);
329 return (count($a) && in_array($s,$a));
333 * Compare activity uri. Knows about activity namespace.
335 * @param string $haystack
336 * @param string $needle
339 function activity_match($haystack,$needle) {
340 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
345 * @brief Pull out all #hashtags and @person tags from $string.
347 * We also get @person@domain.com - which would make
348 * the regex quite complicated as tags can also
349 * end a sentence. So we'll run through our results
350 * and strip the period from any tags which end with one.
351 * Returns array of tags found, or empty array.
353 * @param string $string Post content
354 * @return array List of tag and person names
356 function get_tags($string) {
359 // Convert hashtag links to hashtags
360 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
362 // ignore anything in a code block
363 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
365 // Force line feeds at bbtags
366 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
368 // ignore anything in a bbtag
369 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
371 // Match full names against @tags including the space between first and last
372 // We will look these up afterward to see if they are full names or not recognisable.
374 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
375 foreach ($matches[1] as $match) {
376 if (strstr($match, ']')) {
377 // we might be inside a bbcode color tag - leave it alone
380 if (substr($match, -1, 1) === '.') {
381 $ret[] = substr($match, 0, -1);
388 // Otherwise pull out single word tags. These can be @nickname, @first_last
391 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
392 foreach ($matches[1] as $match) {
393 if (strstr($match, ']')) {
394 // we might be inside a bbcode color tag - leave it alone
397 if (substr($match, -1, 1) === '.') {
398 $match = substr($match,0,-1);
400 // ignore strictly numeric tags like #1
401 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
404 // try not to catch url fragments
405 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
416 * quick and dirty quoted_printable encoding
422 return str_replace("%", "=", rawurlencode($s));
427 * Get html for contact block.
429 * @template contact_block.tpl
430 * @hook contact_block_end (contacts=>array, output=>string)
433 function contact_block() {
437 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
442 if (!is_array($a->profile) || $a->profile['hide-friends']) {
445 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
446 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
447 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
448 AND `network` IN ('%s', '%s', '%s')",
449 intval($a->profile['uid']),
450 DBA::escape(Protocol::DFRN),
451 DBA::escape(Protocol::OSTATUS),
452 DBA::escape(Protocol::DIASPORA)
454 if (DBA::isResult($r)) {
455 $total = intval($r[0]['total']);
458 $contacts = L10n::t('No contacts');
461 // Splitting the query in two parts makes it much faster
462 $r = q("SELECT `id` FROM `contact`
463 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
464 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
465 AND `network` IN ('%s', '%s', '%s')
466 ORDER BY RAND() LIMIT %d",
467 intval($a->profile['uid']),
468 DBA::escape(Protocol::DFRN),
469 DBA::escape(Protocol::OSTATUS),
470 DBA::escape(Protocol::DIASPORA),
473 if (DBA::isResult($r)) {
475 foreach ($r AS $contact) {
476 $contacts[] = $contact["id"];
478 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
479 DBA::escape(implode(",", $contacts)));
481 if (DBA::isResult($r)) {
482 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
484 foreach ($r as $rr) {
485 $micropro[] = micropro($rr, true, 'mpfriend');
491 $tpl = Renderer::getMarkupTemplate('contact_block.tpl');
492 $o = Renderer::replaceMacros($tpl, [
493 '$contacts' => $contacts,
494 '$nickname' => $a->profile['nickname'],
495 '$viewcontacts' => L10n::t('View Contacts'),
496 '$micropro' => $micropro,
499 $arr = ['contacts' => $r, 'output' => $o];
501 Addon::callHooks('contact_block_end', $arr);
508 * @brief Format contacts as picture links or as texxt links
510 * @param array $contact Array with contacts which contains an array with
511 * int 'id' => The ID of the contact
512 * int 'uid' => The user ID of the user who owns this data
513 * string 'name' => The name of the contact
514 * string 'url' => The url to the profile page of the contact
515 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
516 * string 'network' => The network to which the contact belongs to
517 * string 'thumb' => The contact picture
518 * string 'click' => js code which is performed when clicking on the contact
519 * @param boolean $redirect If true try to use the redir url if it's possible
520 * @param string $class CSS class for the
521 * @param boolean $textmode If true display the contacts as text links
522 * if false display the contacts as picture links
524 * @return string Formatted html
526 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
528 // Use the contact URL if no address is available
529 if (!x($contact, "addr")) {
530 $contact["addr"] = $contact["url"];
533 $url = $contact['url'];
538 $url = Contact::magicLink($contact['url']);
539 if (strpos($url, 'redir/') === 0) {
540 $sparkle = ' sparkle';
544 // If there is some js available we don't need the url
545 if (x($contact, 'click')) {
549 return Renderer::replaceMacros(Renderer::getMarkupTemplate(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
550 '$click' => defaults($contact, 'click', ''),
553 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
554 '$name' => $contact['name'],
555 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
556 '$parkle' => $sparkle,
565 * @param string $s Search query.
566 * @param string $id HTML id
567 * @param string $url Search url.
568 * @param bool $save Show save search button.
569 * @param bool $aside Display the search widgit aside.
571 * @return string Formatted HTML.
573 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
577 if (strpos($s, '#') === 0) {
580 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
583 '$s' => htmlspecialchars($s),
585 '$action_url' => $url,
586 '$search_label' => L10n::t('Search'),
587 '$save_label' => $save_label,
588 '$savedsearch' => local_user() && Feature::isEnabled(local_user(),'savedsearch'),
589 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
594 $values['$searchoption'] = [
595 L10n::t("Full Text"),
597 L10n::t("Contacts")];
599 if (Config::get('system','poco_local_search')) {
600 $values['$searchoption'][] = L10n::t("Forums");
604 return Renderer::replaceMacros(Renderer::getMarkupTemplate('searchbox.tpl'), $values);
608 * @brief Check for a valid email string
610 * @param string $email_address
613 function valid_email($email_address)
615 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
620 * Replace naked text hyperlink with HTML formatted hyperlink
624 function linkify($s) {
625 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
626 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
634 * @return array index is present tense verb
635 * value is array containing past tense verb, translation of present, translation of past
636 * @hook poke_verbs pokes array
638 function get_poke_verbs() {
640 // index is present tense verb
641 // value is array containing past tense verb, translation of present, translation of past
644 'poke' => ['poked', L10n::t('poke'), L10n::t('poked')],
645 'ping' => ['pinged', L10n::t('ping'), L10n::t('pinged')],
646 'prod' => ['prodded', L10n::t('prod'), L10n::t('prodded')],
647 'slap' => ['slapped', L10n::t('slap'), L10n::t('slapped')],
648 'finger' => ['fingered', L10n::t('finger'), L10n::t('fingered')],
649 'rebuff' => ['rebuffed', L10n::t('rebuff'), L10n::t('rebuffed')],
651 Addon::callHooks('poke_verbs', $arr);
656 * @brief Translate days and months names.
658 * @param string $s String with day or month name.
659 * @return string Translated string.
661 function day_translate($s) {
662 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
663 [L10n::t('Monday'), L10n::t('Tuesday'), L10n::t('Wednesday'), L10n::t('Thursday'), L10n::t('Friday'), L10n::t('Saturday'), L10n::t('Sunday')],
666 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
667 [L10n::t('January'), L10n::t('February'), L10n::t('March'), L10n::t('April'), L10n::t('May'), L10n::t('June'), L10n::t('July'), L10n::t('August'), L10n::t('September'), L10n::t('October'), L10n::t('November'), L10n::t('December')],
674 * @brief Translate short days and months names.
676 * @param string $s String with short day or month name.
677 * @return string Translated string.
679 function day_short_translate($s) {
680 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
681 [L10n::t('Mon'), L10n::t('Tue'), L10n::t('Wed'), L10n::t('Thu'), L10n::t('Fri'), L10n::t('Sat'), L10n::t('Sun')],
683 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
684 [L10n::t('Jan'), L10n::t('Feb'), L10n::t('Mar'), L10n::t('Apr'), L10n::t('May'), ('Jun'), L10n::t('Jul'), L10n::t('Aug'), L10n::t('Sep'), L10n::t('Oct'), L10n::t('Nov'), L10n::t('Dec')],
696 function normalise_link($url) {
697 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
698 return rtrim($ret,'/');
703 * Compare two URLs to see if they are the same, but ignore
704 * slight but hopefully insignificant differences such as if one
705 * is https and the other isn't, or if one is www.something and
706 * the other isn't - and also ignore case differences.
708 * @param string $a first url
709 * @param string $b second url
710 * @return boolean True if the URLs match, otherwise False
713 function link_compare($a, $b) {
714 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
719 * @brief Find any non-embedded images in private items and add redir links to them
722 * @param array &$item The field array of an item row
724 function redir_private_images($a, &$item)
727 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
729 foreach ($matches as $mtch) {
730 if (strpos($mtch[1], '/redir') !== false) {
734 if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == Protocol::DFRN)) {
735 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
736 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
743 * Sets the "rendered-html" field of the provided item
745 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
748 * @param bool $update
750 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
752 function put_item_in_cache(&$item, $update = false)
754 $body = $item["body"];
756 $rendered_hash = defaults($item, 'rendered-hash', '');
757 $rendered_html = defaults($item, 'rendered-html', '');
759 if ($rendered_hash == ''
760 || $rendered_html == ""
761 || $rendered_hash != hash("md5", $item["body"])
762 || Config::get("system", "ignore_cache")
765 redir_private_images($a, $item);
767 $item["rendered-html"] = prepare_text($item["body"]);
768 $item["rendered-hash"] = hash("md5", $item["body"]);
770 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
771 Addon::callHooks('put_item_in_cache', $hook_data);
772 $item['rendered-html'] = $hook_data['rendered-html'];
773 $item['rendered-hash'] = $hook_data['rendered-hash'];
776 // Force an update if the generated values differ from the existing ones
777 if ($rendered_hash != $item["rendered-hash"]) {
781 // Only compare the HTML when we forcefully ignore the cache
782 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
786 if ($update && !empty($item["id"])) {
787 Item::update(['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
788 ['id' => $item["id"]]);
792 $item["body"] = $body;
796 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
797 * If attach is true, also add icons for item attachments.
800 * @param boolean $attach
801 * @param boolean $is_preview
802 * @return string item body html
803 * @hook prepare_body_init item array before any work
804 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
805 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
806 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
808 function prepare_body(array &$item, $attach = false, $is_preview = false)
811 Addon::callHooks('prepare_body_init', $item);
813 // In order to provide theme developers more possibilities, event items
814 // are treated differently.
815 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
816 $ev = Event::getItemHTML($item);
820 $tags = \Friendica\Model\Term::populateTagsFromItem($item);
822 $item['tags'] = $tags['tags'];
823 $item['hashtags'] = $tags['hashtags'];
824 $item['mentions'] = $tags['mentions'];
826 // Compile eventual content filter reasons
827 $filter_reasons = [];
828 if (!$is_preview && public_contact() != $item['author-id']) {
829 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
830 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
835 'filter_reasons' => $filter_reasons
837 Addon::callHooks('prepare_body_content_filter', $hook_data);
838 $filter_reasons = $hook_data['filter_reasons'];
842 // Update the cached values if there is no "zrl=..." on the links.
843 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
845 // Or update it if the current viewer is the intented viewer.
846 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
850 put_item_in_cache($item, $update);
851 $s = $item["rendered-html"];
856 'preview' => $is_preview,
857 'filter_reasons' => $filter_reasons
859 Addon::callHooks('prepare_body', $hook_data);
860 $s = $hook_data['html'];
864 // Replace the blockquotes with quotes that are used in mails.
865 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
866 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
873 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
874 foreach ($matches as $mtch) {
877 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
879 if (strpos($mime, 'video') !== false) {
882 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
883 '$baseurl' => System::baseUrl(),
887 $url_parts = explode('/', $the_url);
888 $id = end($url_parts);
889 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
892 'title' => L10n::t('View Video'),
899 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
901 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
902 $filesubtype = str_replace('.', '-', $filesubtype);
905 $filesubtype = 'unkn';
908 $title = escape_tags(trim(!empty($mtch[4]) ? $mtch[4] : $mtch[1]));
909 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
911 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
912 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
916 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
920 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
921 $x = Map::byCoordinates(trim($item['coord']));
923 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
929 $spoilersearch = '<blockquote class="spoiler">';
931 // Remove line breaks before the spoiler.
932 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
933 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
935 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
936 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
939 while ((strpos($s, $spoilersearch) !== false)) {
940 $pos = strpos($s, $spoilersearch);
941 $rnd = random_string(8);
942 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
943 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
944 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
947 // Look for quote with author.
948 $authorsearch = '<blockquote class="author">';
950 while ((strpos($s, $authorsearch) !== false)) {
951 $pos = strpos($s, $authorsearch);
952 $rnd = random_string(8);
953 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
954 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
955 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
958 // Replace friendica image url size with theme preference.
959 if (x($a->theme_info, 'item_image_size')){
960 $ps = $a->theme_info['item_image_size'];
961 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
964 $s = apply_content_filter($s, $filter_reasons);
966 $hook_data = ['item' => $item, 'html' => $s];
967 Addon::callHooks('prepare_body_final', $hook_data);
969 return $hook_data['html'];
973 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
975 * Reasons are expected to have been translated already.
977 * @param string $html
978 * @param array $reasons
981 function apply_content_filter($html, array $reasons)
983 if (count($reasons)) {
984 $tpl = Renderer::getMarkupTemplate('wall/content_filter.tpl');
985 $html = Renderer::replaceMacros($tpl, [
986 '$reasons' => $reasons,
987 '$rnd' => random_string(8),
988 '$openclose' => L10n::t('Click to open/close'),
997 * @brief Given a text string, convert from bbcode to html and add smilie icons.
999 * @param string $text String with bbcode.
1000 * @return string Formattet HTML.
1002 function prepare_text($text) {
1003 if (stristr($text, '[nosmile]')) {
1004 $s = BBCode::convert($text);
1006 $s = Smilies::replace(BBCode::convert($text));
1013 * return array with details for categories and folders for an item
1015 * @param array $item
1019 * [ // categories array
1021 * 'name': 'category name',
1022 * 'removeurl': 'url to remove this category',
1023 * 'first': 'is the first in this array? true/false',
1024 * 'last': 'is the last in this array? true/false',
1030 * 'name': 'folder name',
1031 * 'removeurl': 'url to remove this folder',
1032 * 'first': 'is the first in this array? true/false',
1033 * 'last': 'is the last in this array? true/false',
1039 function get_cats_and_terms($item)
1046 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1048 foreach ($matches as $mtch) {
1050 'name' => xmlify(FileTag::decode($mtch[1])),
1052 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(FileTag::decode($mtch[1])):""),
1060 if (count($categories)) {
1061 $categories[count($categories) - 1]['last'] = true;
1064 if (local_user() == $item['uid']) {
1067 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1069 foreach ($matches as $mtch) {
1071 'name' => xmlify(FileTag::decode($mtch[1])),
1073 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(FileTag::decode($mtch[1])) : ""),
1082 if (count($folders)) {
1083 $folders[count($folders) - 1]['last'] = true;
1086 return [$categories, $folders];
1091 * get private link for item
1092 * @param array $item
1093 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1095 function get_plink($item) {
1098 if ($a->user['nickname'] != "") {
1100 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1101 'href' => "display/" . $item['guid'],
1102 'orig' => "display/" . $item['guid'],
1103 'title' => L10n::t('View on separate page'),
1104 'orig_title' => L10n::t('view on separate page'),
1107 if (x($item, 'plink')) {
1108 $ret["href"] = $a->removeBaseURL($item['plink']);
1109 $ret["title"] = L10n::t('link to source');
1112 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1114 'href' => $item['plink'],
1115 'orig' => $item['plink'],
1116 'title' => L10n::t('link to source'),
1127 * replace html amp entity with amp char
1131 function unamp($s) {
1132 return str_replace('&', '&', $s);
1137 * return number of bytes in size (K, M, G)
1138 * @param string $size_str
1141 function return_bytes($size_str) {
1142 switch (substr ($size_str, -1)) {
1143 case 'M': case 'm': return (int)$size_str * 1048576;
1144 case 'K': case 'k': return (int)$size_str * 1024;
1145 case 'G': case 'g': return (int)$size_str * 1073741824;
1146 default: return $size_str;
1152 * @param boolean $strip_padding
1155 function base64url_encode($s, $strip_padding = false) {
1157 $s = strtr(base64_encode($s), '+/', '-_');
1159 if ($strip_padding) {
1160 $s = str_replace('=','',$s);
1170 function base64url_decode($s) {
1173 Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1178 * // Placeholder for new rev of salmon which strips base64 padding.
1179 * // PHP base64_decode handles the un-padded input without requiring this step
1180 * // Uncomment if you find you need it.
1183 * if (!strpos($s,'=')) {
1193 return base64_decode(strtr($s,'-_','+/'));
1198 * return div element with class 'clear'
1202 function cleardiv() {
1203 return '<div class="clear"></div>';
1207 function bb_translate_video($s) {
1210 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1212 foreach ($matches as $mtch) {
1213 if ((stristr($mtch[1], 'youtube')) || (stristr($mtch[1], 'youtu.be'))) {
1214 $s = str_replace($mtch[0], '[youtube]' . $mtch[1] . '[/youtube]', $s);
1215 } elseif (stristr($mtch[1], 'vimeo')) {
1216 $s = str_replace($mtch[0], '[vimeo]' . $mtch[1] . '[/vimeo]', $s);
1223 function html2bb_video($s) {
1225 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1226 '[youtube]$2[/youtube]', $s);
1228 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1229 '[youtube]$2[/youtube]', $s);
1231 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1232 '[vimeo]$2[/vimeo]', $s);
1238 * apply xmlify() to all values of array $val, recursively
1242 function array_xmlify($val){
1243 if (is_bool($val)) {
1244 return $val?"true":"false";
1245 } elseif (is_array($val)) {
1246 return array_map('array_xmlify', $val);
1248 return xmlify((string) $val);
1253 * transform link href and img src from relative to absolute
1255 * @param string $text
1256 * @param string $base base url
1259 function reltoabs($text, $base) {
1264 $base = rtrim($base,'/');
1266 $base2 = $base . "/";
1269 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1270 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1271 $text = preg_replace($pattern, $replace, $text);
1273 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1274 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1275 $text = preg_replace($pattern, $replace, $text);
1278 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1279 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1280 $text = preg_replace($pattern, $replace, $text);
1282 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1283 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1284 $text = preg_replace($pattern, $replace, $text);
1292 * get translated item type
1294 * @param array $itme
1297 function item_post_type($item) {
1298 if (!empty($item['event-id'])) {
1299 return L10n::t('event');
1300 } elseif (!empty($item['resource-id'])) {
1301 return L10n::t('photo');
1302 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1303 return L10n::t('activity');
1304 } elseif ($item['id'] != $item['parent']) {
1305 return L10n::t('comment');
1308 return L10n::t('post');
1311 function normalise_openid($s) {
1312 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1316 function undo_post_tagging($s) {
1318 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1320 foreach ($matches as $mtch) {
1321 if (in_array($mtch[1], ['!', '@'])) {
1322 $contact = Contact::getDetailsByURL($mtch[2]);
1323 $mtch[3] = empty($contact['addr']) ? $mtch[2] : $contact['addr'];
1325 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1331 function protect_sprintf($s) {
1332 return str_replace('%', '%%', $s);
1335 /// @TODO Rewrite this
1336 function is_a_date_arg($s) {
1342 if ($i <= $y + 1 && strpos($s, '-') == 4) {
1343 $m = intval(substr($s, 5));
1345 if ($m > 0 && $m <= 12) {
1355 * remove intentation from a text
1357 function deindent($text, $chr = "[\t ]", $count = NULL) {
1358 $lines = explode("\n", $text);
1360 if (is_null($count)) {
1363 while ($k < count($lines) && strlen($lines[$k]) == 0) {
1366 preg_match("|^" . $chr . "*|", $lines[$k], $m);
1367 $count = strlen($m[0]);
1370 for ($k = 0; $k < count($lines); $k++) {
1371 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
1374 return implode("\n", $lines);
1377 function formatBytes($bytes, $precision = 2) {
1378 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
1380 $bytes = max($bytes, 0);
1381 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
1382 $pow = min($pow, count($units) - 1);
1384 $bytes /= pow(1024, $pow);
1386 return round($bytes, $precision) . ' ' . $units[$pow];
1390 * @brief translate and format the networkname of a contact
1392 * @param string $network
1393 * Networkname of the contact (e.g. dfrn, rss and so on)
1398 function format_network_name($network, $url = 0) {
1399 if ($network != "") {
1401 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
1403 $network_name = ContactSelector::networkToName($network);
1406 return $network_name;