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;
28 require_once "include/conversation.php";
31 * This is our template processor
33 * @param string|FriendicaSmarty $s the string requiring macro substitution,
34 * or an instance of FriendicaSmarty
35 * @param array $r key value pairs (search => replace)
36 * @return string substituted string
38 function replace_macros($s, $r) {
40 $stamp1 = microtime(true);
44 // pass $baseurl to all templates
45 $r['$baseurl'] = System::baseUrl();
47 $t = $a->getTemplateEngine();
49 $output = $t->replaceMacros($s, $r);
50 } catch (Exception $e) {
51 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
55 $a->saveTimestamp($stamp1, "rendering");
61 * @brief Generates a pseudo-random string of hexadecimal characters
66 function random_string($size = 64)
68 $byte_size = ceil($size / 2);
70 $bytes = random_bytes($byte_size);
72 $return = substr(bin2hex($bytes), 0, $size);
78 * This is our primary input filter.
80 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
81 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
82 * after cleansing, and angle chars with the high bit set could get through as markup.
84 * This is now disabled because it was interfering with some legitimate unicode sequences
85 * and hopefully there aren't a lot of those browsers left.
87 * Use this on any text input where angle chars are not valid or permitted
88 * They will be replaced with safer brackets. This may be filtered further
89 * if these are not allowed either.
91 * @param string $string Input string
92 * @return string Filtered string
94 function notags($string) {
95 return str_replace(["<", ">"], ['[', ']'], $string);
97 // High-bit filter no longer used
98 // return str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string);
103 * use this on "body" or "content" input where angle chars shouldn't be removed,
104 * and allow them to be safely displayed.
105 * @param string $string
108 function escape_tags($string) {
109 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
114 * generate a string that's random, but usually pronounceable.
115 * used to generate initial passwords
119 function autoname($len) {
125 $vowels = ['a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'];
126 if (mt_rand(0, 5) == 4) {
145 's','sc','sh','sm','sp','st',
153 $midcons = ['ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
154 'nd','ng','nk','nt','rn','rp','rt'];
156 $noend = ['bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
157 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh','q'];
159 $start = mt_rand(0,2);
168 for ($x = 0; $x < $len; $x ++) {
169 $r = mt_rand(0,count($table) - 1);
172 if ($table == $vowels) {
173 $table = array_merge($cons,$midcons);
180 $word = substr($word,0,$len);
182 foreach ($noend as $noe) {
183 $noelen = strlen($noe);
184 if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
185 $word = autoname($len);
195 * escape text ($str) for XML transport
197 * @return string Escaped text.
199 function xmlify($str) {
200 /// @TODO deprecated code found?
203 $len = mb_strlen($str);
204 for ($x = 0; $x < $len; $x ++) {
205 $char = mb_substr($str,$x,1);
235 $buffer = mb_ereg_replace("&", "&", $str);
236 $buffer = mb_ereg_replace("'", "'", $buffer);
237 $buffer = mb_ereg_replace('"', """, $buffer);
238 $buffer = mb_ereg_replace("<", "<", $buffer);
239 $buffer = mb_ereg_replace(">", ">", $buffer);
241 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
242 $buffer = trim($buffer);
250 * @param string $s xml escaped text
251 * @return string unescaped text
253 function unxmlify($s) {
254 /// @TODO deprecated code found?
255 // $ret = str_replace('&','&', $s);
256 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
257 /*$ret = mb_ereg_replace('&', '&', $s);
258 $ret = mb_ereg_replace(''', "'", $ret);
259 $ret = mb_ereg_replace('"', '"', $ret);
260 $ret = mb_ereg_replace('<', "<", $ret);
261 $ret = mb_ereg_replace('>', ">", $ret);
263 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
268 * Loader for infinite scrolling
269 * @return string html for loader
271 function scroll_loader() {
272 $tpl = get_markup_template("scroll_loader.tpl");
273 return replace_macros($tpl, [
274 'wait' => L10n::t('Loading more entries...'),
275 'end' => L10n::t('The end')
281 * Turn user/group ACLs stored as angle bracketed text into arrays
286 function expand_acl($s) {
287 // turn string array of angle-bracketed elements into numeric array
288 // e.g. "<1><2><3>" => array(1,2,3);
292 $t = str_replace('<', '', $s);
293 $a = explode('>', $t);
294 foreach ($a as $aa) {
296 $ret[] = intval($aa);
305 * Wrap ACL elements in angle brackets for storage
306 * @param string $item
308 function sanitise_acl(&$item) {
310 $item = '<' . intval(notags(trim($item))) . '>';
318 * Convert an ACL array to a storable string
320 * Normally ACL permissions will be an array.
321 * We'll also allow a comma-separated string.
323 * @param string|array $p
326 function perms2str($p) {
331 $tmp = explode(',', $p);
334 if (is_array($tmp)) {
335 array_walk($tmp, 'sanitise_acl');
336 $ret = implode('', $tmp);
345 * @param string $root
348 function get_markup_template($s, $root = '') {
349 $stamp1 = microtime(true);
352 $t = $a->getTemplateEngine();
354 $template = $t->getTemplateFile($s, $root);
355 } catch (Exception $e) {
356 echo "<pre><b>" . __FUNCTION__ . "</b>: " . $e->getMessage() . "</pre>";
360 $a->saveTimestamp($stamp1, "file");
366 * for html,xml parsing - let's say you've got
367 * an attribute foobar="class1 class2 class3"
368 * and you want to find out if it contains 'class3'.
369 * you can't use a normal sub string search because you
370 * might match 'notclass3' and a regex to do the job is
371 * possible but a bit complicated.
372 * pass the attribute string as $attr and the attribute you
373 * are looking for as $s - returns true if found, otherwise false
375 * @param string $attr attribute value
376 * @param string $s string to search
377 * @return boolean True if found, False otherwise
379 function attribute_contains($attr, $s) {
380 $a = explode(' ', $attr);
381 return (count($a) && in_array($s,$a));
386 * @brief Logs the given message at the given log level
390 * LOGGER_INFO (default)
396 * @global array $LOGGER_LEVELS
400 function logger($msg, $level = LOGGER_INFO)
402 Logger::log($msg, $level);
406 * @brief An alternative logger for development.
407 * Works largely as logger() but allows developers
408 * to isolate particular elements they are targetting
409 * personally without background noise
413 * LOGGER_INFO (default)
419 * @global array $LOGGER_LEVELS
423 function dlogger($msg, $level = LOGGER_INFO)
425 Logger::devLog($msg, $level);
430 * Compare activity uri. Knows about activity namespace.
432 * @param string $haystack
433 * @param string $needle
436 function activity_match($haystack,$needle) {
437 return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA)));
442 * @brief Pull out all #hashtags and @person tags from $string.
444 * We also get @person@domain.com - which would make
445 * the regex quite complicated as tags can also
446 * end a sentence. So we'll run through our results
447 * and strip the period from any tags which end with one.
448 * Returns array of tags found, or empty array.
450 * @param string $string Post content
451 * @return array List of tag and person names
453 function get_tags($string) {
456 // Convert hashtag links to hashtags
457 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
459 // ignore anything in a code block
460 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
462 // Force line feeds at bbtags
463 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
465 // ignore anything in a bbtag
466 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
468 // Match full names against @tags including the space between first and last
469 // We will look these up afterward to see if they are full names or not recognisable.
471 if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
472 foreach ($matches[1] as $match) {
473 if (strstr($match, ']')) {
474 // we might be inside a bbcode color tag - leave it alone
477 if (substr($match, -1, 1) === '.') {
478 $ret[] = substr($match, 0, -1);
485 // Otherwise pull out single word tags. These can be @nickname, @first_last
488 if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
489 foreach ($matches[1] as $match) {
490 if (strstr($match, ']')) {
491 // we might be inside a bbcode color tag - leave it alone
494 if (substr($match, -1, 1) === '.') {
495 $match = substr($match,0,-1);
497 // ignore strictly numeric tags like #1
498 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
501 // try not to catch url fragments
502 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
513 * quick and dirty quoted_printable encoding
519 return str_replace("%", "=", rawurlencode($s));
524 * Get html for contact block.
526 * @template contact_block.tpl
527 * @hook contact_block_end (contacts=>array, output=>string)
530 function contact_block() {
534 $shown = PConfig::get($a->profile['uid'], 'system', 'display_friend_count', 24);
539 if (!is_array($a->profile) || $a->profile['hide-friends']) {
542 $r = q("SELECT COUNT(*) AS `total` FROM `contact`
543 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
544 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
545 AND `network` IN ('%s', '%s', '%s')",
546 intval($a->profile['uid']),
547 DBA::escape(Protocol::DFRN),
548 DBA::escape(Protocol::OSTATUS),
549 DBA::escape(Protocol::DIASPORA)
551 if (DBA::isResult($r)) {
552 $total = intval($r[0]['total']);
555 $contacts = L10n::t('No contacts');
558 // Splitting the query in two parts makes it much faster
559 $r = q("SELECT `id` FROM `contact`
560 WHERE `uid` = %d AND NOT `self` AND NOT `blocked`
561 AND NOT `pending` AND NOT `hidden` AND NOT `archive`
562 AND `network` IN ('%s', '%s', '%s')
563 ORDER BY RAND() LIMIT %d",
564 intval($a->profile['uid']),
565 DBA::escape(Protocol::DFRN),
566 DBA::escape(Protocol::OSTATUS),
567 DBA::escape(Protocol::DIASPORA),
570 if (DBA::isResult($r)) {
572 foreach ($r AS $contact) {
573 $contacts[] = $contact["id"];
575 $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `thumb`, `network` FROM `contact` WHERE `id` IN (%s)",
576 DBA::escape(implode(",", $contacts)));
578 if (DBA::isResult($r)) {
579 $contacts = L10n::tt('%d Contact', '%d Contacts', $total);
581 foreach ($r as $rr) {
582 $micropro[] = micropro($rr, true, 'mpfriend');
588 $tpl = get_markup_template('contact_block.tpl');
589 $o = replace_macros($tpl, [
590 '$contacts' => $contacts,
591 '$nickname' => $a->profile['nickname'],
592 '$viewcontacts' => L10n::t('View Contacts'),
593 '$micropro' => $micropro,
596 $arr = ['contacts' => $r, 'output' => $o];
598 Addon::callHooks('contact_block_end', $arr);
605 * @brief Format contacts as picture links or as texxt links
607 * @param array $contact Array with contacts which contains an array with
608 * int 'id' => The ID of the contact
609 * int 'uid' => The user ID of the user who owns this data
610 * string 'name' => The name of the contact
611 * string 'url' => The url to the profile page of the contact
612 * string 'addr' => The webbie of the contact (e.g.) username@friendica.com
613 * string 'network' => The network to which the contact belongs to
614 * string 'thumb' => The contact picture
615 * string 'click' => js code which is performed when clicking on the contact
616 * @param boolean $redirect If true try to use the redir url if it's possible
617 * @param string $class CSS class for the
618 * @param boolean $textmode If true display the contacts as text links
619 * if false display the contacts as picture links
621 * @return string Formatted html
623 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
625 // Use the contact URL if no address is available
626 if (!x($contact, "addr")) {
627 $contact["addr"] = $contact["url"];
630 $url = $contact['url'];
635 $url = Contact::magicLink($contact['url']);
636 if (strpos($url, 'redir/') === 0) {
637 $sparkle = ' sparkle';
641 // If there is some js available we don't need the url
642 if (x($contact, 'click')) {
646 return replace_macros(get_markup_template(($textmode)?'micropro_txt.tpl':'micropro_img.tpl'),[
647 '$click' => defaults($contact, 'click', ''),
650 '$photo' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
651 '$name' => $contact['name'],
652 'title' => $contact['name'] . ' [' . $contact['addr'] . ']',
653 '$parkle' => $sparkle,
662 * @param string $s Search query.
663 * @param string $id HTML id
664 * @param string $url Search url.
665 * @param bool $save Show save search button.
666 * @param bool $aside Display the search widgit aside.
668 * @return string Formatted HTML.
670 function search($s, $id = 'search-box', $url = 'search', $save = false, $aside = true)
674 if (strpos($s, '#') === 0) {
677 $save_label = $mode === 'text' ? L10n::t('Save') : L10n::t('Follow');
680 '$s' => htmlspecialchars($s),
682 '$action_url' => $url,
683 '$search_label' => L10n::t('Search'),
684 '$save_label' => $save_label,
685 '$savedsearch' => local_user() && Feature::isEnabled(local_user(),'savedsearch'),
686 '$search_hint' => L10n::t('@name, !forum, #tags, content'),
691 $values['$searchoption'] = [
692 L10n::t("Full Text"),
694 L10n::t("Contacts")];
696 if (Config::get('system','poco_local_search')) {
697 $values['$searchoption'][] = L10n::t("Forums");
701 return replace_macros(get_markup_template('searchbox.tpl'), $values);
705 * @brief Check for a valid email string
707 * @param string $email_address
710 function valid_email($email_address)
712 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
717 * Replace naked text hyperlink with HTML formatted hyperlink
721 function linkify($s) {
722 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="_blank">$1</a>', $s);
723 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
731 * @return array index is present tense verb
732 * value is array containing past tense verb, translation of present, translation of past
733 * @hook poke_verbs pokes array
735 function get_poke_verbs() {
737 // index is present tense verb
738 // value is array containing past tense verb, translation of present, translation of past
741 'poke' => ['poked', L10n::t('poke'), L10n::t('poked')],
742 'ping' => ['pinged', L10n::t('ping'), L10n::t('pinged')],
743 'prod' => ['prodded', L10n::t('prod'), L10n::t('prodded')],
744 'slap' => ['slapped', L10n::t('slap'), L10n::t('slapped')],
745 'finger' => ['fingered', L10n::t('finger'), L10n::t('fingered')],
746 'rebuff' => ['rebuffed', L10n::t('rebuff'), L10n::t('rebuffed')],
748 Addon::callHooks('poke_verbs', $arr);
753 * @brief Translate days and months names.
755 * @param string $s String with day or month name.
756 * @return string Translated string.
758 function day_translate($s) {
759 $ret = str_replace(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
760 [L10n::t('Monday'), L10n::t('Tuesday'), L10n::t('Wednesday'), L10n::t('Thursday'), L10n::t('Friday'), L10n::t('Saturday'), L10n::t('Sunday')],
763 $ret = str_replace(['January','February','March','April','May','June','July','August','September','October','November','December'],
764 [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')],
771 * @brief Translate short days and months names.
773 * @param string $s String with short day or month name.
774 * @return string Translated string.
776 function day_short_translate($s) {
777 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
778 [L10n::t('Mon'), L10n::t('Tue'), L10n::t('Wed'), L10n::t('Thu'), L10n::t('Fri'), L10n::t('Sat'), L10n::t('Sun')],
780 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'],
781 [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')],
793 function normalise_link($url) {
794 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
795 return rtrim($ret,'/');
800 * Compare two URLs to see if they are the same, but ignore
801 * slight but hopefully insignificant differences such as if one
802 * is https and the other isn't, or if one is www.something and
803 * the other isn't - and also ignore case differences.
805 * @param string $a first url
806 * @param string $b second url
807 * @return boolean True if the URLs match, otherwise False
810 function link_compare($a, $b) {
811 return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
816 * @brief Find any non-embedded images in private items and add redir links to them
819 * @param array &$item The field array of an item row
821 function redir_private_images($a, &$item)
824 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
826 foreach ($matches as $mtch) {
827 if (strpos($mtch[1], '/redir') !== false) {
831 if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == Protocol::DFRN)) {
832 $img_url = 'redir?f=1&quiet=1&url=' . urlencode($mtch[1]) . '&conurl=' . urlencode($item['author-link']);
833 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
840 * Sets the "rendered-html" field of the provided item
842 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
845 * @param bool $update
847 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
849 function put_item_in_cache(&$item, $update = false)
851 $body = $item["body"];
853 $rendered_hash = defaults($item, 'rendered-hash', '');
854 $rendered_html = defaults($item, 'rendered-html', '');
856 if ($rendered_hash == ''
857 || $rendered_html == ""
858 || $rendered_hash != hash("md5", $item["body"])
859 || Config::get("system", "ignore_cache")
862 redir_private_images($a, $item);
864 $item["rendered-html"] = prepare_text($item["body"]);
865 $item["rendered-hash"] = hash("md5", $item["body"]);
867 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
868 Addon::callHooks('put_item_in_cache', $hook_data);
869 $item['rendered-html'] = $hook_data['rendered-html'];
870 $item['rendered-hash'] = $hook_data['rendered-hash'];
873 // Force an update if the generated values differ from the existing ones
874 if ($rendered_hash != $item["rendered-hash"]) {
878 // Only compare the HTML when we forcefully ignore the cache
879 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
883 if ($update && !empty($item["id"])) {
884 Item::update(['rendered-html' => $item["rendered-html"], 'rendered-hash' => $item["rendered-hash"]],
885 ['id' => $item["id"]]);
889 $item["body"] = $body;
893 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
894 * If attach is true, also add icons for item attachments.
897 * @param boolean $attach
898 * @param boolean $is_preview
899 * @return string item body html
900 * @hook prepare_body_init item array before any work
901 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
902 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
903 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
905 function prepare_body(array &$item, $attach = false, $is_preview = false)
908 Addon::callHooks('prepare_body_init', $item);
910 // In order to provide theme developers more possibilities, event items
911 // are treated differently.
912 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
913 $ev = Event::getItemHTML($item);
917 $tags = \Friendica\Model\Term::populateTagsFromItem($item);
919 $item['tags'] = $tags['tags'];
920 $item['hashtags'] = $tags['hashtags'];
921 $item['mentions'] = $tags['mentions'];
923 // Compile eventual content filter reasons
924 $filter_reasons = [];
925 if (!$is_preview && public_contact() != $item['author-id']) {
926 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
927 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
932 'filter_reasons' => $filter_reasons
934 Addon::callHooks('prepare_body_content_filter', $hook_data);
935 $filter_reasons = $hook_data['filter_reasons'];
939 // Update the cached values if there is no "zrl=..." on the links.
940 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
942 // Or update it if the current viewer is the intented viewer.
943 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
947 put_item_in_cache($item, $update);
948 $s = $item["rendered-html"];
953 'preview' => $is_preview,
954 'filter_reasons' => $filter_reasons
956 Addon::callHooks('prepare_body', $hook_data);
957 $s = $hook_data['html'];
961 // Replace the blockquotes with quotes that are used in mails.
962 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
963 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
970 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
971 foreach ($matches as $mtch) {
974 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
976 if (strpos($mime, 'video') !== false) {
979 $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), [
980 '$baseurl' => System::baseUrl(),
984 $url_parts = explode('/', $the_url);
985 $id = end($url_parts);
986 $as .= replace_macros(get_markup_template('video_top.tpl'), [
989 'title' => L10n::t('View Video'),
996 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
998 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
999 $filesubtype = str_replace('.', '-', $filesubtype);
1002 $filesubtype = 'unkn';
1005 $title = escape_tags(trim(!empty($mtch[4]) ? $mtch[4] : $mtch[1]));
1006 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
1008 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1009 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
1013 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
1017 if (strpos($s, '<div class="map">') !== false && x($item, 'coord')) {
1018 $x = Map::byCoordinates(trim($item['coord']));
1020 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
1025 // Look for spoiler.
1026 $spoilersearch = '<blockquote class="spoiler">';
1028 // Remove line breaks before the spoiler.
1029 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
1030 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
1032 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
1033 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
1036 while ((strpos($s, $spoilersearch) !== false)) {
1037 $pos = strpos($s, $spoilersearch);
1038 $rnd = random_string(8);
1039 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1040 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
1041 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
1044 // Look for quote with author.
1045 $authorsearch = '<blockquote class="author">';
1047 while ((strpos($s, $authorsearch) !== false)) {
1048 $pos = strpos($s, $authorsearch);
1049 $rnd = random_string(8);
1050 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
1051 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
1052 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
1055 // Replace friendica image url size with theme preference.
1056 if (x($a->theme_info, 'item_image_size')){
1057 $ps = $a->theme_info['item_image_size'];
1058 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
1061 $s = apply_content_filter($s, $filter_reasons);
1063 $hook_data = ['item' => $item, 'html' => $s];
1064 Addon::callHooks('prepare_body_final', $hook_data);
1066 return $hook_data['html'];
1070 * Given a HTML text and a set of filtering reasons, adds a content hiding header with the provided reasons
1072 * Reasons are expected to have been translated already.
1074 * @param string $html
1075 * @param array $reasons
1078 function apply_content_filter($html, array $reasons)
1080 if (count($reasons)) {
1081 $tpl = get_markup_template('wall/content_filter.tpl');
1082 $html = replace_macros($tpl, [
1083 '$reasons' => $reasons,
1084 '$rnd' => random_string(8),
1085 '$openclose' => L10n::t('Click to open/close'),
1094 * @brief Given a text string, convert from bbcode to html and add smilie icons.
1096 * @param string $text String with bbcode.
1097 * @return string Formattet HTML.
1099 function prepare_text($text) {
1100 if (stristr($text, '[nosmile]')) {
1101 $s = BBCode::convert($text);
1103 $s = Smilies::replace(BBCode::convert($text));
1110 * return array with details for categories and folders for an item
1112 * @param array $item
1116 * [ // categories array
1118 * 'name': 'category name',
1119 * 'removeurl': 'url to remove this category',
1120 * 'first': 'is the first in this array? true/false',
1121 * 'last': 'is the last in this array? true/false',
1127 * 'name': 'folder name',
1128 * 'removeurl': 'url to remove this folder',
1129 * 'first': 'is the first in this array? true/false',
1130 * 'last': 'is the last in this array? true/false',
1136 function get_cats_and_terms($item)
1143 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1145 foreach ($matches as $mtch) {
1147 'name' => xmlify(file_tag_decode($mtch[1])),
1149 'removeurl' => ((local_user() == $item['uid'])?'filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1157 if (count($categories)) {
1158 $categories[count($categories) - 1]['last'] = true;
1161 if (local_user() == $item['uid']) {
1164 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1166 foreach ($matches as $mtch) {
1168 'name' => xmlify(file_tag_decode($mtch[1])),
1170 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) : ""),
1179 if (count($folders)) {
1180 $folders[count($folders) - 1]['last'] = true;
1183 return [$categories, $folders];
1188 * get private link for item
1189 * @param array $item
1190 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1192 function get_plink($item) {
1195 if ($a->user['nickname'] != "") {
1197 //'href' => "display/" . $a->user['nickname'] . "/" . $item['id'],
1198 'href' => "display/" . $item['guid'],
1199 'orig' => "display/" . $item['guid'],
1200 'title' => L10n::t('View on separate page'),
1201 'orig_title' => L10n::t('view on separate page'),
1204 if (x($item, 'plink')) {
1205 $ret["href"] = $a->removeBaseURL($item['plink']);
1206 $ret["title"] = L10n::t('link to source');
1209 } elseif (x($item, 'plink') && ($item['private'] != 1)) {
1211 'href' => $item['plink'],
1212 'orig' => $item['plink'],
1213 'title' => L10n::t('link to source'),
1224 * replace html amp entity with amp char
1228 function unamp($s) {
1229 return str_replace('&', '&', $s);
1234 * return number of bytes in size (K, M, G)
1235 * @param string $size_str
1238 function return_bytes($size_str) {
1239 switch (substr ($size_str, -1)) {
1240 case 'M': case 'm': return (int)$size_str * 1048576;
1241 case 'K': case 'k': return (int)$size_str * 1024;
1242 case 'G': case 'g': return (int)$size_str * 1073741824;
1243 default: return $size_str;
1249 * @param boolean $strip_padding
1252 function base64url_encode($s, $strip_padding = false) {
1254 $s = strtr(base64_encode($s), '+/', '-_');
1256 if ($strip_padding) {
1257 $s = str_replace('=','',$s);
1267 function base64url_decode($s) {
1270 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1275 * // Placeholder for new rev of salmon which strips base64 padding.
1276 * // PHP base64_decode handles the un-padded input without requiring this step
1277 * // Uncomment if you find you need it.
1280 * if (!strpos($s,'=')) {
1290 return base64_decode(strtr($s,'-_','+/'));
1295 * return div element with class 'clear'
1299 function cleardiv() {
1300 return '<div class="clear"></div>';
1304 function bb_translate_video($s) {
1307 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1309 foreach ($matches as $mtch) {
1310 if ((stristr($mtch[1], 'youtube')) || (stristr($mtch[1], 'youtu.be'))) {
1311 $s = str_replace($mtch[0], '[youtube]' . $mtch[1] . '[/youtube]', $s);
1312 } elseif (stristr($mtch[1], 'vimeo')) {
1313 $s = str_replace($mtch[0], '[vimeo]' . $mtch[1] . '[/vimeo]', $s);
1320 function html2bb_video($s) {
1322 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1323 '[youtube]$2[/youtube]', $s);
1325 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1326 '[youtube]$2[/youtube]', $s);
1328 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1329 '[vimeo]$2[/vimeo]', $s);
1335 * apply xmlify() to all values of array $val, recursively
1339 function array_xmlify($val){
1340 if (is_bool($val)) {
1341 return $val?"true":"false";
1342 } elseif (is_array($val)) {
1343 return array_map('array_xmlify', $val);
1345 return xmlify((string) $val);
1350 * transform link href and img src from relative to absolute
1352 * @param string $text
1353 * @param string $base base url
1356 function reltoabs($text, $base) {
1361 $base = rtrim($base,'/');
1363 $base2 = $base . "/";
1366 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1367 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1368 $text = preg_replace($pattern, $replace, $text);
1370 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1371 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1372 $text = preg_replace($pattern, $replace, $text);
1375 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1376 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1377 $text = preg_replace($pattern, $replace, $text);
1379 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1380 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1381 $text = preg_replace($pattern, $replace, $text);
1389 * get translated item type
1391 * @param array $itme
1394 function item_post_type($item) {
1395 if (!empty($item['event-id'])) {
1396 return L10n::t('event');
1397 } elseif (!empty($item['resource-id'])) {
1398 return L10n::t('photo');
1399 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
1400 return L10n::t('activity');
1401 } elseif ($item['id'] != $item['parent']) {
1402 return L10n::t('comment');
1405 return L10n::t('post');
1408 // post categories and "save to file" use the same item.file table for storage.
1409 // We will differentiate the different uses by wrapping categories in angle brackets
1410 // and save to file categories in square brackets.
1411 // To do this we need to escape these characters if they appear in our tag.
1413 function file_tag_encode($s) {
1414 return str_replace(['<','>','[',']'],['%3c','%3e','%5b','%5d'],$s);
1417 function file_tag_decode($s) {
1418 return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
1421 function file_tag_file_query($table,$s,$type = 'file') {
1423 if ($type == 'file') {
1424 $str = preg_quote('[' . str_replace('%', '%%', file_tag_encode($s)) . ']');
1426 $str = preg_quote('<' . str_replace('%', '%%', file_tag_encode($s)) . '>');
1428 return " AND " . (($table) ? DBA::escape($table) . '.' : '') . "file regexp '" . DBA::escape($str) . "' ";
1431 // ex. given music,video return <music><video> or [music][video]
1432 function file_tag_list_to_file($list, $type = 'file') {
1434 if (strlen($list)) {
1435 $list_array = explode(",",$list);
1436 if ($type == 'file') {
1444 foreach ($list_array as $item) {
1445 if (strlen($item)) {
1446 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1453 // ex. given <music><video>[friends], return music,video or friends
1454 function file_tag_file_to_list($file, $type = 'file') {
1457 if ($type == 'file') {
1458 $cnt = preg_match_all('/\[(.*?)\]/', $file, $matches, PREG_SET_ORDER);
1460 $cnt = preg_match_all('/<(.*?)>/', $file, $matches, PREG_SET_ORDER);
1463 foreach ($matches as $mtch) {
1464 if (strlen($list)) {
1467 $list .= file_tag_decode($mtch[1]);
1474 function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
1475 // $file_old - categories previously associated with an item
1476 // $file_new - new list of categories for an item
1478 if (!intval($uid)) {
1480 } elseif ($file_old == $file_new) {
1484 $saved = PConfig::get($uid, 'system', 'filetags');
1485 if (strlen($saved)) {
1486 if ($type == 'file') {
1489 $termtype = TERM_FILE;
1493 $termtype = TERM_CATEGORY;
1496 $filetags_updated = $saved;
1498 // check for new tags to be added as filetags in pconfig
1500 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1502 foreach ($check_new_tags as $tag) {
1503 if (!stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket)) {
1508 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1510 // check for deleted tags to be removed from filetags in pconfig
1512 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1514 foreach ($check_deleted_tags as $tag) {
1515 if (!stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket)) {
1516 $deleted_tags[] = $tag;
1520 foreach ($deleted_tags as $key => $tag) {
1521 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1523 intval(TERM_OBJ_POST),
1527 if (DBA::isResult($r)) {
1528 unset($deleted_tags[$key]);
1530 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1534 if ($saved != $filetags_updated) {
1535 PConfig::set($uid, 'system', 'filetags', $filetags_updated);
1538 } elseif (strlen($file_new)) {
1539 PConfig::set($uid, 'system', 'filetags', $file_new);
1544 function file_tag_save_file($uid, $item_id, $file)
1546 if (!intval($uid)) {
1550 $item = Item::selectFirst(['file'], ['id' => $item_id, 'uid' => $uid]);
1551 if (DBA::isResult($item)) {
1552 if (!stristr($item['file'],'[' . file_tag_encode($file) . ']')) {
1553 $fields = ['file' => $item['file'] . '[' . file_tag_encode($file) . ']'];
1554 Item::update($fields, ['id' => $item_id]);
1556 $saved = PConfig::get($uid, 'system', 'filetags');
1557 if (!strlen($saved) || !stristr($saved, '[' . file_tag_encode($file) . ']')) {
1558 PConfig::set($uid, 'system', 'filetags', $saved . '[' . file_tag_encode($file) . ']');
1560 info(L10n::t('Item filed'));
1565 function file_tag_unsave_file($uid, $item_id, $file, $cat = false)
1567 if (!intval($uid)) {
1572 $pattern = '<' . file_tag_encode($file) . '>' ;
1573 $termtype = TERM_CATEGORY;
1575 $pattern = '[' . file_tag_encode($file) . ']' ;
1576 $termtype = TERM_FILE;
1579 $item = Item::selectFirst(['file'], ['id' => $item_id, 'uid' => $uid]);
1580 if (!DBA::isResult($item)) {
1584 $fields = ['file' => str_replace($pattern,'',$item['file'])];
1585 Item::update($fields, ['id' => $item_id]);
1587 $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
1589 intval(TERM_OBJ_POST),
1593 if (!DBA::isResult($r)) {
1594 $saved = PConfig::get($uid, 'system', 'filetags');
1595 PConfig::set($uid, 'system', 'filetags', str_replace($pattern, '', $saved));
1601 function normalise_openid($s) {
1602 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
1606 function undo_post_tagging($s) {
1608 $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER);
1610 foreach ($matches as $mtch) {
1611 if (in_array($mtch[1], ['!', '@'])) {
1612 $contact = Contact::getDetailsByURL($mtch[2]);
1613 $mtch[3] = empty($contact['addr']) ? $mtch[2] : $contact['addr'];
1615 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1621 function protect_sprintf($s) {
1622 return str_replace('%', '%%', $s);
1625 /// @TODO Rewrite this
1626 function is_a_date_arg($s) {
1632 if ($i <= $y + 1 && strpos($s, '-') == 4) {
1633 $m = intval(substr($s, 5));
1635 if ($m > 0 && $m <= 12) {
1645 * remove intentation from a text
1647 function deindent($text, $chr = "[\t ]", $count = NULL) {
1648 $lines = explode("\n", $text);
1650 if (is_null($count)) {
1653 while ($k < count($lines) && strlen($lines[$k]) == 0) {
1656 preg_match("|^" . $chr . "*|", $lines[$k], $m);
1657 $count = strlen($m[0]);
1660 for ($k = 0; $k < count($lines); $k++) {
1661 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
1664 return implode("\n", $lines);
1667 function formatBytes($bytes, $precision = 2) {
1668 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
1670 $bytes = max($bytes, 0);
1671 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
1672 $pow = min($pow, count($units) - 1);
1674 $bytes /= pow(1024, $pow);
1676 return round($bytes, $precision) . ' ' . $units[$pow];
1680 * @brief translate and format the networkname of a contact
1682 * @param string $network
1683 * Networkname of the contact (e.g. dfrn, rss and so on)
1688 function format_network_name($network, $url = 0) {
1689 if ($network != "") {
1691 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
1693 $network_name = ContactSelector::networkToName($network);
1696 return $network_name;