3 * @file src/Content/Text/BBCode.php
5 namespace Friendica\Content\Text;
8 use Friendica\Content\Text\Plaintext;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Object\Image;
14 use Friendica\Util\ParseUrl;
16 require_once "include/bbcode.php";
17 require_once "include/html2plain.php";
22 * @brief Fetches attachment data that were generated the old way
24 * @param string $body Message body
26 * 'type' -> Message type ("link", "video", "photo")
27 * 'text' -> Text before the shared message
28 * 'after' -> Text after the shared message
29 * 'image' -> Preview image of the message
30 * 'url' -> Url to the attached message
31 * 'title' -> Title of the attachment
32 * 'description' -> Description of the attachment
34 private static function getOldAttachmentData($body)
38 // Simplify image codes
39 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
41 if (preg_match_all("(\[class=(.*?)\](.*?)\[\/class\])ism", $body, $attached, PREG_SET_ORDER)) {
42 foreach ($attached as $data) {
43 if (!in_array($data[1], ["type-link", "type-video", "type-photo"])) {
47 $post["type"] = substr($data[1], 5);
49 $pos = strpos($body, $data[0]);
51 $post["text"] = trim(substr($body, 0, $pos));
52 $post["after"] = trim(substr($body, $pos + strlen($data[0])));
54 $post["text"] = trim(str_replace($data[0], "", $body));
57 $attacheddata = $data[2];
59 $URLSearchString = "^\[\]";
61 if (preg_match("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $attacheddata, $matches)) {
63 $picturedata = Image::getInfoFromURL($matches[1]);
65 if (($picturedata[0] >= 500) && ($picturedata[0] >= $picturedata[1])) {
66 $post["image"] = $matches[1];
68 $post["preview"] = $matches[1];
72 if (preg_match("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", $attacheddata, $matches)) {
73 $post["url"] = $matches[1];
74 $post["title"] = $matches[2];
76 if (($post["url"] == "") && (in_array($post["type"], ["link", "video"]))
77 && preg_match("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $attacheddata, $matches)) {
78 $post["url"] = $matches[1];
81 // Search for description
82 if (preg_match("/\[quote\](.*?)\[\/quote\]/ism", $attacheddata, $matches)) {
83 $post["description"] = $matches[1];
91 * @brief Fetches attachment data that were generated with the "attachment" element
93 * @param string $body Message body
95 * 'type' -> Message type ("link", "video", "photo")
96 * 'text' -> Text before the shared message
97 * 'after' -> Text after the shared message
98 * 'image' -> Preview image of the message
99 * 'url' -> Url to the attached message
100 * 'title' -> Title of the attachment
101 * 'description' -> Description of the attachment
103 public static function getAttachmentData($body)
107 if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
108 return self::getOldAttachmentData($body);
111 $attributes = $match[2];
113 $data["text"] = trim($match[1]);
116 preg_match("/type='(.*?)'/ism", $attributes, $matches);
117 if (x($matches, 1)) {
118 $type = strtolower($matches[1]);
121 preg_match('/type="(.*?)"/ism', $attributes, $matches);
122 if (x($matches, 1)) {
123 $type = strtolower($matches[1]);
130 if (!in_array($type, ["link", "audio", "photo", "video"])) {
135 $data["type"] = $type;
139 preg_match("/url='(.*?)'/ism", $attributes, $matches);
140 if (x($matches, 1)) {
144 preg_match('/url="(.*?)"/ism', $attributes, $matches);
145 if (x($matches, 1)) {
150 $data["url"] = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
154 preg_match("/title='(.*?)'/ism", $attributes, $matches);
155 if (x($matches, 1)) {
156 $title = $matches[1];
159 preg_match('/title="(.*?)"/ism', $attributes, $matches);
160 if (x($matches, 1)) {
161 $title = $matches[1];
165 $title = bbcode(html_entity_decode($title, ENT_QUOTES, 'UTF-8'), false, false, true);
166 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
167 $title = str_replace(["[", "]"], ["[", "]"], $title);
168 $data["title"] = $title;
172 preg_match("/image='(.*?)'/ism", $attributes, $matches);
173 if (x($matches, 1)) {
174 $image = $matches[1];
177 preg_match('/image="(.*?)"/ism', $attributes, $matches);
178 if (x($matches, 1)) {
179 $image = $matches[1];
183 $data["image"] = html_entity_decode($image, ENT_QUOTES, 'UTF-8');
187 preg_match("/preview='(.*?)'/ism", $attributes, $matches);
188 if (x($matches, 1)) {
189 $preview = $matches[1];
192 preg_match('/preview="(.*?)"/ism', $attributes, $matches);
193 if (x($matches, 1)) {
194 $preview = $matches[1];
197 if ($preview != "") {
198 $data["preview"] = html_entity_decode($preview, ENT_QUOTES, 'UTF-8');
201 $data["description"] = trim($match[3]);
203 $data["after"] = trim($match[4]);
208 public static function getAttachedData($body, $item = [])
212 - type: link, video, photo
220 $has_title = !empty($item['title']);
221 $plink = (!empty($item['plink']) ? $item['plink'] : '');
222 $post = self::getAttachmentData($body);
224 // if nothing is found, it maybe having an image.
225 if (!isset($post["type"])) {
226 // Simplify image codes
227 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
229 $URLSearchString = "^\[\]";
230 if (preg_match_all("(\[url=([$URLSearchString]*)\]\s*\[img\]([$URLSearchString]*)\[\/img\]\s*\[\/url\])ism", $body, $pictures, PREG_SET_ORDER)) {
231 if ((count($pictures) == 1) && !$has_title) {
232 // Checking, if the link goes to a picture
233 $data = ParseUrl::getSiteinfoCached($pictures[0][1], true);
236 // Sometimes photo posts to the own album are not detected at the start.
237 // So we seem to cannot use the cache for these cases. That's strange.
238 if (($data["type"] != "photo") && strstr($pictures[0][1], "/photos/")) {
239 $data = ParseUrl::getSiteinfo($pictures[0][1], true);
242 if ($data["type"] == "photo") {
243 $post["type"] = "photo";
244 if (isset($data["images"][0])) {
245 $post["image"] = $data["images"][0]["src"];
246 $post["url"] = $data["url"];
248 $post["image"] = $data["url"];
251 $post["preview"] = $pictures[0][2];
252 $post["text"] = str_replace($pictures[0][0], "", $body);
254 $imgdata = Image::getInfoFromURL($pictures[0][1]);
255 if (substr($imgdata["mime"], 0, 6) == "image/") {
256 $post["type"] = "photo";
257 $post["image"] = $pictures[0][1];
258 $post["preview"] = $pictures[0][2];
259 $post["text"] = str_replace($pictures[0][0], "", $body);
262 } elseif (count($pictures) > 0) {
263 $post["type"] = "link";
264 $post["url"] = $plink;
265 $post["image"] = $pictures[0][2];
266 $post["text"] = $body;
268 } elseif (preg_match_all("(\[img\]([$URLSearchString]*)\[\/img\])ism", $body, $pictures, PREG_SET_ORDER)) {
269 if ((count($pictures) == 1) && !$has_title) {
270 $post["type"] = "photo";
271 $post["image"] = $pictures[0][1];
272 $post["text"] = str_replace($pictures[0][0], "", $body);
273 } elseif (count($pictures) > 0) {
274 $post["type"] = "link";
275 $post["url"] = $plink;
276 $post["image"] = $pictures[0][1];
277 $post["text"] = $body;
281 // Test for the external links
282 preg_match_all("(\[url\]([$URLSearchString]*)\[\/url\])ism", $body, $links1, PREG_SET_ORDER);
283 preg_match_all("(\[url\=([$URLSearchString]*)\].*?\[\/url\])ism", $body, $links2, PREG_SET_ORDER);
285 $links = array_merge($links1, $links2);
287 // If there is only a single one, then use it.
288 // This should cover link posts via API.
289 if ((count($links) == 1) && !isset($post["preview"]) && !$has_title) {
290 $post["type"] = "link";
291 $post["text"] = trim($body);
292 $post["url"] = $links[0][1];
295 // Now count the number of external media links
296 preg_match_all("(\[vimeo\](.*?)\[\/vimeo\])ism", $body, $links1, PREG_SET_ORDER);
297 preg_match_all("(\[youtube\\](.*?)\[\/youtube\\])ism", $body, $links2, PREG_SET_ORDER);
298 preg_match_all("(\[video\\](.*?)\[\/video\\])ism", $body, $links3, PREG_SET_ORDER);
299 preg_match_all("(\[audio\\](.*?)\[\/audio\\])ism", $body, $links4, PREG_SET_ORDER);
301 // Add them to the other external links
302 $links = array_merge($links, $links1, $links2, $links3, $links4);
304 // Are there more than one?
305 if (count($links) > 1) {
306 // The post will be the type "text", which means a blog post
307 unset($post["type"]);
308 $post["url"] = $plink;
311 if (!isset($post["type"])) {
312 $post["type"] = "text";
313 $post["text"] = trim($body);
315 } elseif (isset($post["url"]) && ($post["type"] == "video")) {
316 $data = ParseUrl::getSiteinfoCached($post["url"], true);
318 if (isset($data["images"][0])) {
319 $post["image"] = $data["images"][0]["src"];
327 * @brief Convert a message into plaintext for connectors to other networks
329 * @param array $b The message array that is about to be posted
330 * @param int $limit The maximum number of characters when posting to that network
331 * @param bool $includedlinks Has an attached link to be included into the message?
332 * @param int $htmlmode This triggers the behaviour of the bbcode conversion
333 * @param string $target_network Name of the network where the post should go to.
335 * @return string The converted message
337 public static function toPlaintext($b, $limit = 0, $includedlinks = false, $htmlmode = 2, $target_network = "")
339 // Remove the hash tags
340 $URLSearchString = "^\[\]";
341 $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $b["body"]);
343 // Add an URL element if the text contains a raw link
344 $body = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url]$2[/url]', $body);
346 // Remove the abstract
347 $body = remove_abstract($body);
349 // At first look at data that is attached via "type-..." stuff
350 // This will hopefully replaced with a dedicated bbcode later
351 //$post = self::getAttachedData($b["body"]);
352 $post = self::getAttachedData($body, $b);
354 if (($b["title"] != "") && ($post["text"] != "")) {
355 $post["text"] = trim($b["title"]."\n\n".$post["text"]);
356 } elseif ($b["title"] != "") {
357 $post["text"] = trim($b["title"]);
362 // Fetch the abstract from the given target network
363 if ($target_network != "") {
364 $default_abstract = fetch_abstract($b["body"]);
365 $abstract = fetch_abstract($b["body"], $target_network);
367 // If we post to a network with no limit we only fetch
368 // an abstract exactly for this network
369 if (($limit == 0) && ($abstract == $default_abstract)) {
372 } else {// Try to guess the correct target network
375 $abstract = fetch_abstract($b["body"], NETWORK_TWITTER);
378 $abstract = fetch_abstract($b["body"], NETWORK_STATUSNET);
381 $abstract = fetch_abstract($b["body"], NETWORK_APPNET);
383 default: // We don't know the exact target.
384 // We fetch an abstract since there is a posting limit.
386 $abstract = fetch_abstract($b["body"]);
391 if ($abstract != "") {
392 $post["text"] = $abstract;
394 if ($post["type"] == "text") {
395 $post["type"] = "link";
396 $post["url"] = $b["plink"];
400 $html = bbcode($post["text"].$post["after"], false, false, $htmlmode);
401 $msg = html2plain($html, 0, true);
402 $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8'));
405 if ($includedlinks) {
406 if ($post["type"] == "link") {
407 $link = $post["url"];
408 } elseif ($post["type"] == "text") {
409 $link = $post["url"];
410 } elseif ($post["type"] == "video") {
411 $link = $post["url"];
412 } elseif ($post["type"] == "photo") {
413 $link = $post["image"];
416 if (($msg == "") && isset($post["title"])) {
417 $msg = trim($post["title"]);
420 if (($msg == "") && isset($post["description"])) {
421 $msg = trim($post["description"]);
424 // If the link is already contained in the post, then it neeedn't to be added again
425 // But: if the link is beyond the limit, then it has to be added.
426 if (($link != "") && strstr($msg, $link)) {
427 $pos = strpos($msg, $link);
429 // Will the text be shortened in the link?
430 // Or is the link the last item in the post?
431 if (($limit > 0) && ($pos < $limit) && (($pos + 23 > $limit) || ($pos + strlen($link) == strlen($msg)))) {
432 $msg = trim(str_replace($link, "", $msg));
433 } elseif (($limit == 0) || ($pos < $limit)) {
434 // The limit has to be increased since it will be shortened - but not now
435 // Only do it with Twitter (htmlmode = 8)
436 if (($limit > 0) && (strlen($link) > 23) && ($htmlmode == 8)) {
437 $limit = $limit - 23 + strlen($link);
442 if ($post["type"] == "text") {
450 // Reduce multiple spaces
451 // When posted to a network with limited space, we try to gain space where possible
452 while (strpos($msg, " ") !== false) {
453 $msg = str_replace(" ", " ", $msg);
456 // Twitter is using its own limiter, so we always assume that shortened links will have this length
457 if (iconv_strlen($link, "UTF-8") > 0) {
458 $limit = $limit - 23;
461 if (iconv_strlen($msg, "UTF-8") > $limit) {
462 if (($post["type"] == "text") && isset($post["url"])) {
463 $post["url"] = $b["plink"];
464 } elseif (!isset($post["url"])) {
465 $limit = $limit - 23;
466 $post["url"] = $b["plink"];
467 // Which purpose has this line? It is now uncommented, but left as a reminder
468 //} elseif (strpos($b["body"], "[share") !== false) {
469 // $post["url"] = $b["plink"];
470 } elseif (PConfig::get($b["uid"], "system", "no_intelligent_shortening")) {
471 $post["url"] = $b["plink"];
473 $msg = Plaintext::shorten($msg, $limit);
477 $post["text"] = trim($msg);
482 public static function scaleExternalImages($srctext, $include_link = true, $scale_replace = false)
484 // Suppress "view full size"
485 if (intval(Config::get('system', 'no_view_full_size'))) {
486 $include_link = false;
489 // Picture addresses can contain special characters
490 $s = htmlspecialchars_decode($srctext);
493 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
495 foreach ($matches as $mtch) {
496 logger('scale_external_image: ' . $mtch[1]);
498 $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
499 if (stristr($mtch[1], $hostname)) {
503 // $scale_replace, if passed, is an array of two elements. The
504 // first is the name of the full-size image. The second is the
505 // name of a remote, scaled-down version of the full size image.
506 // This allows Friendica to display the smaller remote image if
507 // one exists, while still linking to the full-size image
508 if ($scale_replace) {
509 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
513 $i = self::fetchURL($scaled);
518 // guess mimetype from headers or filename
519 $type = Image::guessType($mtch[1], true);
522 $Image = new Image($i, $type);
523 if ($Image->isValid()) {
524 $orig_width = $Image->getWidth();
525 $orig_height = $Image->getHeight();
527 if ($orig_width > 640 || $orig_height > 640) {
528 $Image->scaleDown(640);
529 $new_width = $Image->getWidth();
530 $new_height = $Image->getHeight();
531 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
534 '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
535 . "\n" . (($include_link)
536 ? '[url=' . $mtch[1] . ']' . L10n::t('view full size') . '[/url]' . "\n"
540 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
547 // replace the special char encoding
548 $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');