Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1986 lines
68 KiB

  1. <?php
  2. /**
  3. * @file src/Content/Text/BBCode.php
  4. */
  5. namespace Friendica\Content\Text;
  6. use DOMDocument;
  7. use Exception;
  8. use Friendica\Content\OEmbed;
  9. use Friendica\Content\Smilies;
  10. use Friendica\Content\Text\Plaintext;
  11. use Friendica\Core\Addon;
  12. use Friendica\Core\Cache;
  13. use Friendica\Core\Config;
  14. use Friendica\Core\L10n;
  15. use Friendica\Core\Network;
  16. use Friendica\Core\PConfig;
  17. use Friendica\Core\System;
  18. use Friendica\Model\Contact;
  19. use Friendica\Object\Image;
  20. use Friendica\Util\Map;
  21. use Friendica\Util\Network as NetworkUtil;
  22. use Friendica\Util\ParseUrl;
  23. require_once "include/bbcode.php";
  24. require_once "include/event.php";
  25. require_once "include/html2plain.php";
  26. require_once "mod/proxy.php";
  27. class BBCode
  28. {
  29. /**
  30. * @brief Fetches attachment data that were generated the old way
  31. *
  32. * @param string $body Message body
  33. * @return array
  34. * 'type' -> Message type ("link", "video", "photo")
  35. * 'text' -> Text before the shared message
  36. * 'after' -> Text after the shared message
  37. * 'image' -> Preview image of the message
  38. * 'url' -> Url to the attached message
  39. * 'title' -> Title of the attachment
  40. * 'description' -> Description of the attachment
  41. */
  42. private static function getOldAttachmentData($body)
  43. {
  44. $post = [];
  45. // Simplify image codes
  46. $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
  47. if (preg_match_all("(\[class=(.*?)\](.*?)\[\/class\])ism", $body, $attached, PREG_SET_ORDER)) {
  48. foreach ($attached as $data) {
  49. if (!in_array($data[1], ["type-link", "type-video", "type-photo"])) {
  50. continue;
  51. }
  52. $post["type"] = substr($data[1], 5);
  53. $pos = strpos($body, $data[0]);
  54. if ($pos > 0) {
  55. $post["text"] = trim(substr($body, 0, $pos));
  56. $post["after"] = trim(substr($body, $pos + strlen($data[0])));
  57. } else {
  58. $post["text"] = trim(str_replace($data[0], "", $body));
  59. }
  60. $attacheddata = $data[2];
  61. $URLSearchString = "^\[\]";
  62. if (preg_match("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $attacheddata, $matches)) {
  63. $picturedata = Image::getInfoFromURL($matches[1]);
  64. if (($picturedata[0] >= 500) && ($picturedata[0] >= $picturedata[1])) {
  65. $post["image"] = $matches[1];
  66. } else {
  67. $post["preview"] = $matches[1];
  68. }
  69. }
  70. if (preg_match("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", $attacheddata, $matches)) {
  71. $post["url"] = $matches[1];
  72. $post["title"] = $matches[2];
  73. }
  74. if (($post["url"] == "") && (in_array($post["type"], ["link", "video"]))
  75. && preg_match("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $attacheddata, $matches)) {
  76. $post["url"] = $matches[1];
  77. }
  78. // Search for description
  79. if (preg_match("/\[quote\](.*?)\[\/quote\]/ism", $attacheddata, $matches)) {
  80. $post["description"] = $matches[1];
  81. }
  82. }
  83. }
  84. return $post;
  85. }
  86. /**
  87. * @brief Fetches attachment data that were generated with the "attachment" element
  88. *
  89. * @param string $body Message body
  90. * @return array
  91. * 'type' -> Message type ("link", "video", "photo")
  92. * 'text' -> Text before the shared message
  93. * 'after' -> Text after the shared message
  94. * 'image' -> Preview image of the message
  95. * 'url' -> Url to the attached message
  96. * 'title' -> Title of the attachment
  97. * 'description' -> Description of the attachment
  98. */
  99. public static function getAttachmentData($body)
  100. {
  101. $data = [];
  102. if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
  103. return self::getOldAttachmentData($body);
  104. }
  105. $attributes = $match[2];
  106. $data["text"] = trim($match[1]);
  107. $type = "";
  108. preg_match("/type='(.*?)'/ism", $attributes, $matches);
  109. if (x($matches, 1)) {
  110. $type = strtolower($matches[1]);
  111. }
  112. preg_match('/type="(.*?)"/ism', $attributes, $matches);
  113. if (x($matches, 1)) {
  114. $type = strtolower($matches[1]);
  115. }
  116. if ($type == "") {
  117. return [];
  118. }
  119. if (!in_array($type, ["link", "audio", "photo", "video"])) {
  120. return [];
  121. }
  122. if ($type != "") {
  123. $data["type"] = $type;
  124. }
  125. $url = "";
  126. preg_match("/url='(.*?)'/ism", $attributes, $matches);
  127. if (x($matches, 1)) {
  128. $url = $matches[1];
  129. }
  130. preg_match('/url="(.*?)"/ism', $attributes, $matches);
  131. if (x($matches, 1)) {
  132. $url = $matches[1];
  133. }
  134. if ($url != "") {
  135. $data["url"] = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
  136. }
  137. $title = "";
  138. preg_match("/title='(.*?)'/ism", $attributes, $matches);
  139. if (x($matches, 1)) {
  140. $title = $matches[1];
  141. }
  142. preg_match('/title="(.*?)"/ism', $attributes, $matches);
  143. if (x($matches, 1)) {
  144. $title = $matches[1];
  145. }
  146. if ($title != "") {
  147. $title = bbcode(html_entity_decode($title, ENT_QUOTES, 'UTF-8'), false, false, true);
  148. $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
  149. $title = str_replace(["[", "]"], ["&#91;", "&#93;"], $title);
  150. $data["title"] = $title;
  151. }
  152. $image = "";
  153. preg_match("/image='(.*?)'/ism", $attributes, $matches);
  154. if (x($matches, 1)) {
  155. $image = $matches[1];
  156. }
  157. preg_match('/image="(.*?)"/ism', $attributes, $matches);
  158. if (x($matches, 1)) {
  159. $image = $matches[1];
  160. }
  161. if ($image != "") {
  162. $data["image"] = html_entity_decode($image, ENT_QUOTES, 'UTF-8');
  163. }
  164. $preview = "";
  165. preg_match("/preview='(.*?)'/ism", $attributes, $matches);
  166. if (x($matches, 1)) {
  167. $preview = $matches[1];
  168. }
  169. preg_match('/preview="(.*?)"/ism', $attributes, $matches);
  170. if (x($matches, 1)) {
  171. $preview = $matches[1];
  172. }
  173. if ($preview != "") {
  174. $data["preview"] = html_entity_decode($preview, ENT_QUOTES, 'UTF-8');
  175. }
  176. $data["description"] = trim($match[3]);
  177. $data["after"] = trim($match[4]);
  178. return $data;
  179. }
  180. public static function getAttachedData($body, $item = [])
  181. {
  182. /*
  183. - text:
  184. - type: link, video, photo
  185. - title:
  186. - url:
  187. - image:
  188. - description:
  189. - (thumbnail)
  190. */
  191. $has_title = !empty($item['title']);
  192. $plink = (!empty($item['plink']) ? $item['plink'] : '');
  193. $post = self::getAttachmentData($body);
  194. // if nothing is found, it maybe having an image.
  195. if (!isset($post["type"])) {
  196. // Simplify image codes
  197. $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
  198. $URLSearchString = "^\[\]";
  199. if (preg_match_all("(\[url=([$URLSearchString]*)\]\s*\[img\]([$URLSearchString]*)\[\/img\]\s*\[\/url\])ism", $body, $pictures, PREG_SET_ORDER)) {
  200. if ((count($pictures) == 1) && !$has_title) {
  201. // Checking, if the link goes to a picture
  202. $data = ParseUrl::getSiteinfoCached($pictures[0][1], true);
  203. // Workaround:
  204. // Sometimes photo posts to the own album are not detected at the start.
  205. // So we seem to cannot use the cache for these cases. That's strange.
  206. if (($data["type"] != "photo") && strstr($pictures[0][1], "/photos/")) {
  207. $data = ParseUrl::getSiteinfo($pictures[0][1], true);
  208. }
  209. if ($data["type"] == "photo") {
  210. $post["type"] = "photo";
  211. if (isset($data["images"][0])) {
  212. $post["image"] = $data["images"][0]["src"];
  213. $post["url"] = $data["url"];
  214. } else {
  215. $post["image"] = $data["url"];
  216. }
  217. $post["preview"] = $pictures[0][2];
  218. $post["text"] = str_replace($pictures[0][0], "", $body);
  219. } else {
  220. $imgdata = Image::getInfoFromURL($pictures[0][1]);
  221. if (substr($imgdata["mime"], 0, 6) == "image/") {
  222. $post["type"] = "photo";
  223. $post["image"] = $pictures[0][1];
  224. $post["preview"] = $pictures[0][2];
  225. $post["text"] = str_replace($pictures[0][0], "", $body);
  226. }
  227. }
  228. } elseif (count($pictures) > 0) {
  229. $post["type"] = "link";
  230. $post["url"] = $plink;
  231. $post["image"] = $pictures[0][2];
  232. $post["text"] = $body;
  233. }
  234. } elseif (preg_match_all("(\[img\]([$URLSearchString]*)\[\/img\])ism", $body, $pictures, PREG_SET_ORDER)) {
  235. if ((count($pictures) == 1) && !$has_title) {
  236. $post["type"] = "photo";
  237. $post["image"] = $pictures[0][1];
  238. $post["text"] = str_replace($pictures[0][0], "", $body);
  239. } elseif (count($pictures) > 0) {
  240. $post["type"] = "link";
  241. $post["url"] = $plink;
  242. $post["image"] = $pictures[0][1];
  243. $post["text"] = $body;
  244. }
  245. }
  246. // Test for the external links
  247. preg_match_all("(\[url\]([$URLSearchString]*)\[\/url\])ism", $body, $links1, PREG_SET_ORDER);
  248. preg_match_all("(\[url\=([$URLSearchString]*)\].*?\[\/url\])ism", $body, $links2, PREG_SET_ORDER);
  249. $links = array_merge($links1, $links2);
  250. // If there is only a single one, then use it.
  251. // This should cover link posts via API.
  252. if ((count($links) == 1) && !isset($post["preview"]) && !$has_title) {
  253. $post["type"] = "link";
  254. $post["text"] = trim($body);
  255. $post["url"] = $links[0][1];
  256. }
  257. // Now count the number of external media links
  258. preg_match_all("(\[vimeo\](.*?)\[\/vimeo\])ism", $body, $links1, PREG_SET_ORDER);
  259. preg_match_all("(\[youtube\\](.*?)\[\/youtube\\])ism", $body, $links2, PREG_SET_ORDER);
  260. preg_match_all("(\[video\\](.*?)\[\/video\\])ism", $body, $links3, PREG_SET_ORDER);
  261. preg_match_all("(\[audio\\](.*?)\[\/audio\\])ism", $body, $links4, PREG_SET_ORDER);
  262. // Add them to the other external links
  263. $links = array_merge($links, $links1, $links2, $links3, $links4);
  264. // Are there more than one?
  265. if (count($links) > 1) {
  266. // The post will be the type "text", which means a blog post
  267. unset($post["type"]);
  268. $post["url"] = $plink;
  269. }
  270. if (!isset($post["type"])) {
  271. $post["type"] = "text";
  272. $post["text"] = trim($body);
  273. }
  274. } elseif (isset($post["url"]) && ($post["type"] == "video")) {
  275. $data = ParseUrl::getSiteinfoCached($post["url"], true);
  276. if (isset($data["images"][0])) {
  277. $post["image"] = $data["images"][0]["src"];
  278. }
  279. }
  280. return $post;
  281. }
  282. /**
  283. * @brief Convert a message into plaintext for connectors to other networks
  284. *
  285. * @param array $b The message array that is about to be posted
  286. * @param int $limit The maximum number of characters when posting to that network
  287. * @param bool $includedlinks Has an attached link to be included into the message?
  288. * @param int $htmlmode This triggers the behaviour of the bbcode conversion
  289. * @param string $target_network Name of the network where the post should go to.
  290. *
  291. * @return string The converted message
  292. */
  293. public static function toPlaintext($b, $limit = 0, $includedlinks = false, $htmlmode = 2, $target_network = "")
  294. {
  295. // Remove the hash tags
  296. $URLSearchString = "^\[\]";
  297. $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $b["body"]);
  298. // Add an URL element if the text contains a raw link
  299. $body = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url]$2[/url]', $body);
  300. // Remove the abstract
  301. $body = self::stripAbstract($body);
  302. // At first look at data that is attached via "type-..." stuff
  303. // This will hopefully replaced with a dedicated bbcode later
  304. //$post = self::getAttachedData($b["body"]);
  305. $post = self::getAttachedData($body, $b);
  306. if (($b["title"] != "") && ($post["text"] != "")) {
  307. $post["text"] = trim($b["title"]."\n\n".$post["text"]);
  308. } elseif ($b["title"] != "") {
  309. $post["text"] = trim($b["title"]);
  310. }
  311. $abstract = "";
  312. // Fetch the abstract from the given target network
  313. if ($target_network != "") {
  314. $default_abstract = self::getAbstract($b["body"]);
  315. $abstract = self::getAbstract($b["body"], $target_network);
  316. // If we post to a network with no limit we only fetch
  317. // an abstract exactly for this network
  318. if (($limit == 0) && ($abstract == $default_abstract)) {
  319. $abstract = "";
  320. }
  321. } else {// Try to guess the correct target network
  322. switch ($htmlmode) {
  323. case 8:
  324. $abstract = self::getAbstract($b["body"], NETWORK_TWITTER);
  325. break;
  326. case 7:
  327. $abstract = self::getAbstract($b["body"], NETWORK_STATUSNET);
  328. break;
  329. case 6:
  330. $abstract = self::getAbstract($b["body"], NETWORK_APPNET);
  331. break;
  332. default: // We don't know the exact target.
  333. // We fetch an abstract since there is a posting limit.
  334. if ($limit > 0) {
  335. $abstract = self::getAbstract($b["body"]);
  336. }
  337. }
  338. }
  339. if ($abstract != "") {
  340. $post["text"] = $abstract;
  341. if ($post["type"] == "text") {
  342. $post["type"] = "link";
  343. $post["url"] = $b["plink"];
  344. }
  345. }
  346. $html = bbcode($post["text"].$post["after"], false, false, $htmlmode);
  347. $msg = html2plain($html, 0, true);
  348. $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8'));
  349. $link = "";
  350. if ($includedlinks) {
  351. if ($post["type"] == "link") {
  352. $link = $post["url"];
  353. } elseif ($post["type"] == "text") {
  354. $link = $post["url"];
  355. } elseif ($post["type"] == "video") {
  356. $link = $post["url"];
  357. } elseif ($post["type"] == "photo") {
  358. $link = $post["image"];
  359. }
  360. if (($msg == "") && isset($post["title"])) {
  361. $msg = trim($post["title"]);
  362. }
  363. if (($msg == "") && isset($post["description"])) {
  364. $msg = trim($post["description"]);
  365. }
  366. // If the link is already contained in the post, then it neeedn't to be added again
  367. // But: if the link is beyond the limit, then it has to be added.
  368. if (($link != "") && strstr($msg, $link)) {
  369. $pos = strpos($msg, $link);
  370. // Will the text be shortened in the link?
  371. // Or is the link the last item in the post?
  372. if (($limit > 0) && ($pos < $limit) && (($pos + 23 > $limit) || ($pos + strlen($link) == strlen($msg)))) {
  373. $msg = trim(str_replace($link, "", $msg));
  374. } elseif (($limit == 0) || ($pos < $limit)) {
  375. // The limit has to be increased since it will be shortened - but not now
  376. // Only do it with Twitter (htmlmode = 8)
  377. if (($limit > 0) && (strlen($link) > 23) && ($htmlmode == 8)) {
  378. $limit = $limit - 23 + strlen($link);
  379. }
  380. $link = "";
  381. if ($post["type"] == "text") {
  382. unset($post["url"]);
  383. }
  384. }
  385. }
  386. }
  387. if ($limit > 0) {
  388. // Reduce multiple spaces
  389. // When posted to a network with limited space, we try to gain space where possible
  390. while (strpos($msg, " ") !== false) {
  391. $msg = str_replace(" ", " ", $msg);
  392. }
  393. // Twitter is using its own limiter, so we always assume that shortened links will have this length
  394. if (iconv_strlen($link, "UTF-8") > 0) {
  395. $limit = $limit - 23;
  396. }
  397. if (iconv_strlen($msg, "UTF-8") > $limit) {
  398. if (($post["type"] == "text") && isset($post["url"])) {
  399. $post["url"] = $b["plink"];
  400. } elseif (!isset($post["url"])) {
  401. $limit = $limit - 23;
  402. $post["url"] = $b["plink"];
  403. // Which purpose has this line? It is now uncommented, but left as a reminder
  404. //} elseif (strpos($b["body"], "[share") !== false) {
  405. // $post["url"] = $b["plink"];
  406. } elseif (PConfig::get($b["uid"], "system", "no_intelligent_shortening")) {
  407. $post["url"] = $b["plink"];
  408. }
  409. $msg = Plaintext::shorten($msg, $limit);
  410. }
  411. }
  412. $post["text"] = trim($msg);
  413. return($post);
  414. }
  415. public static function scaleExternalImages($srctext, $include_link = true, $scale_replace = false)
  416. {
  417. // Suppress "view full size"
  418. if (intval(Config::get('system', 'no_view_full_size'))) {
  419. $include_link = false;
  420. }
  421. // Picture addresses can contain special characters
  422. $s = htmlspecialchars_decode($srctext);
  423. $matches = null;
  424. $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
  425. if ($c) {
  426. foreach ($matches as $mtch) {
  427. logger('scale_external_image: ' . $mtch[1]);
  428. $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
  429. if (stristr($mtch[1], $hostname)) {
  430. continue;
  431. }
  432. // $scale_replace, if passed, is an array of two elements. The
  433. // first is the name of the full-size image. The second is the
  434. // name of a remote, scaled-down version of the full size image.
  435. // This allows Friendica to display the smaller remote image if
  436. // one exists, while still linking to the full-size image
  437. if ($scale_replace) {
  438. $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
  439. } else {
  440. $scaled = $mtch[1];
  441. }
  442. $i = NetworkUtil::fetchUrl($scaled);
  443. if (!$i) {
  444. return $srctext;
  445. }
  446. // guess mimetype from headers or filename
  447. $type = Image::guessType($mtch[1], true);
  448. if ($i) {
  449. $Image = new Image($i, $type);
  450. if ($Image->isValid()) {
  451. $orig_width = $Image->getWidth();
  452. $orig_height = $Image->getHeight();
  453. if ($orig_width > 640 || $orig_height > 640) {
  454. $Image->scaleDown(640);
  455. $new_width = $Image->getWidth();
  456. $new_height = $Image->getHeight();
  457. logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
  458. $s = str_replace(
  459. $mtch[0],
  460. '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
  461. . "\n" . (($include_link)
  462. ? '[url=' . $mtch[1] . ']' . L10n::t('view full size') . '[/url]' . "\n"
  463. : ''),
  464. $s
  465. );
  466. logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
  467. }
  468. }
  469. }
  470. }
  471. }
  472. // replace the special char encoding
  473. $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
  474. return $s;
  475. }
  476. /**
  477. * The purpose of this function is to apply system message length limits to
  478. * imported messages without including any embedded photos in the length
  479. *
  480. * @brief Truncates imported message body string length to max_import_size
  481. * @param string $body
  482. * @return string
  483. */
  484. public static function limitBodySize($body)
  485. {
  486. $maxlen = get_max_import_size();
  487. // If the length of the body, including the embedded images, is smaller
  488. // than the maximum, then don't waste time looking for the images
  489. if ($maxlen && (strlen($body) > $maxlen)) {
  490. logger('the total body length exceeds the limit', LOGGER_DEBUG);
  491. $orig_body = $body;
  492. $new_body = '';
  493. $textlen = 0;
  494. $img_start = strpos($orig_body, '[img');
  495. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  496. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  497. while (($img_st_close !== false) && ($img_end !== false)) {
  498. $img_st_close++; // make it point to AFTER the closing bracket
  499. $img_end += $img_start;
  500. $img_end += strlen('[/img]');
  501. if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  502. // This is an embedded image
  503. if (($textlen + $img_start) > $maxlen) {
  504. if ($textlen < $maxlen) {
  505. logger('the limit happens before an embedded image', LOGGER_DEBUG);
  506. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  507. $textlen = $maxlen;
  508. }
  509. } else {
  510. $new_body = $new_body . substr($orig_body, 0, $img_start);
  511. $textlen += $img_start;
  512. }
  513. $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
  514. } else {
  515. if (($textlen + $img_end) > $maxlen) {
  516. if ($textlen < $maxlen) {
  517. logger('the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
  518. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  519. $textlen = $maxlen;
  520. }
  521. } else {
  522. $new_body = $new_body . substr($orig_body, 0, $img_end);
  523. $textlen += $img_end;
  524. }
  525. }
  526. $orig_body = substr($orig_body, $img_end);
  527. if ($orig_body === false) {
  528. // in case the body ends on a closing image tag
  529. $orig_body = '';
  530. }
  531. $img_start = strpos($orig_body, '[img');
  532. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  533. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  534. }
  535. if (($textlen + strlen($orig_body)) > $maxlen) {
  536. if ($textlen < $maxlen) {
  537. logger('the limit happens after the end of the last image', LOGGER_DEBUG);
  538. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  539. }
  540. } else {
  541. logger('the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
  542. $new_body = $new_body . $orig_body;
  543. }
  544. return $new_body;
  545. } else {
  546. return $body;
  547. }
  548. }
  549. /**
  550. * Processes [attachment] tags
  551. *
  552. * Note: Can produce a [bookmark] tag in the returned string
  553. *
  554. * @brief Processes [attachment] tags
  555. * @param string $return
  556. * @param bool|int $simplehtml
  557. * @param bool $tryoembed
  558. * @return string
  559. */
  560. private static function convertAttachment($return, $simplehtml = false, $tryoembed = true)
  561. {
  562. $data = self::getAttachmentData($return);
  563. if (!$data) {
  564. return $return;
  565. }
  566. if (isset($data["title"])) {
  567. $data["title"] = strip_tags($data["title"]);
  568. $data["title"] = str_replace(["http://", "https://"], "", $data["title"]);
  569. }
  570. if (((strpos($data["text"], "[img=") !== false) || (strpos($data["text"], "[img]") !== false) || Config::get('system', 'always_show_preview')) && ($data["image"] != "")) {
  571. $data["preview"] = $data["image"];
  572. $data["image"] = "";
  573. }
  574. $return = '';
  575. if ($simplehtml == 7) {
  576. $return = self::convertUrlForMastodon($data["url"]);
  577. } elseif (($simplehtml != 4) && ($simplehtml != 0)) {
  578. $return = sprintf('<a href="%s" target="_blank">%s</a><br>', $data["url"], $data["title"]);
  579. } else {
  580. try {
  581. if ($tryoembed && OEmbed::isAllowedURL($data['url'])) {
  582. $return = OEmbed::getHTML($data['url'], $data['title']);
  583. } else {
  584. throw new Exception('OEmbed is disabled for this attachment.');
  585. }
  586. } catch (Exception $e) {
  587. if ($simplehtml != 4) {
  588. $return = sprintf('<div class="type-%s">', $data["type"]);
  589. }
  590. if ($data["image"] != "") {
  591. $return .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-image" /></a><br />', $data["url"], proxy_url($data["image"]), $data["title"]);
  592. } elseif ($data["preview"] != "") {
  593. $return .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-preview" /></a><br />', $data["url"], proxy_url($data["preview"]), $data["title"]);
  594. }
  595. if (($data["type"] == "photo") && ($data["url"] != "") && ($data["image"] != "")) {
  596. $return .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-image" /></a>', $data["url"], proxy_url($data["image"]), $data["title"]);
  597. } else {
  598. $return .= sprintf('<h4><a href="%s">%s</a></h4>', $data['url'], $data['title']);
  599. }
  600. if ($data["description"] != "" && $data["description"] != $data["title"]) {
  601. $return .= sprintf('<blockquote>%s</blockquote>', trim(bbcode($data["description"])));
  602. }
  603. if ($data["type"] == "link") {
  604. $return .= sprintf('<sup><a href="%s">%s</a></sup>', $data['url'], parse_url($data['url'], PHP_URL_HOST));
  605. }
  606. if ($simplehtml != 4) {
  607. $return .= '</div>';
  608. }
  609. }
  610. }
  611. return trim($data["text"] . ' ' . $return . ' ' . $data["after"]);
  612. }
  613. public static function removeShareInformation($Text, $plaintext = false, $nolink = false)
  614. {
  615. $data = self::getAttachmentData($Text);
  616. if (!$data) {
  617. return $Text;
  618. } elseif ($nolink) {
  619. return $data["text"] . $data["after"];
  620. }
  621. $title = htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false);
  622. $text = htmlentities($data["text"], ENT_QUOTES, 'UTF-8', false);
  623. if ($plaintext || (($title != "") && strstr($text, $title))) {
  624. $data["title"] = $data["url"];
  625. } elseif (($text != "") && strstr($title, $text)) {
  626. $data["text"] = $data["title"];
  627. $data["title"] = $data["url"];
  628. }
  629. if (($data["text"] == "") && ($data["title"] != "") && ($data["url"] == "")) {
  630. return $data["title"] . $data["after"];
  631. }
  632. // If the link already is included in the post, don't add it again
  633. if (($data["url"] != "") && strpos($data["text"], $data["url"])) {
  634. return $data["text"] . $data["after"];
  635. }
  636. $text = $data["text"];
  637. if (($data["url"] != "") && ($data["title"] != "")) {
  638. $text .= "\n[url=" . $data["url"] . "]" . $data["title"] . "[/url]";
  639. } elseif (($data["url"] != "")) {
  640. $text .= "\n" . $data["url"];
  641. }
  642. return $text . "\n" . $data["after"];
  643. }
  644. private static function cleanCss($input)
  645. {
  646. $cleaned = "";
  647. $input = strtolower($input);
  648. for ($i = 0; $i < strlen($input); $i++) {
  649. $char = substr($input, $i, 1);
  650. if (($char >= "a") && ($char <= "z")) {
  651. $cleaned .= $char;
  652. }
  653. if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
  654. $cleaned .= $char;
  655. }
  656. }
  657. return $cleaned;
  658. }
  659. /**
  660. * Converts [url] BBCodes in a format that looks fine on Mastodon. (callback function)
  661. *
  662. * @brief Converts [url] BBCodes in a format that looks fine on Mastodon. (callback function)
  663. * @param array $match Array with the matching values
  664. * @return string reformatted link including HTML codes
  665. */
  666. private static function convertUrlForMastodonCallback($match)
  667. {
  668. $url = $match[1];
  669. if (isset($match[2]) && ($match[1] != $match[2])) {
  670. return $match[0];
  671. }
  672. $parts = parse_url($url);
  673. if (!isset($parts['scheme'])) {
  674. return $match[0];
  675. }
  676. return self::convertUrlForMastodon($url);
  677. }
  678. /**
  679. * @brief Converts [url] BBCodes in a format that looks fine on Mastodon and GNU Social.
  680. * @param string $url URL that is about to be reformatted
  681. * @return string reformatted link including HTML codes
  682. */
  683. private static function convertUrlForMastodon($url)
  684. {
  685. $parts = parse_url($url);
  686. $scheme = $parts['scheme'] . '://';
  687. $styled_url = str_replace($scheme, '', $url);
  688. $html = '<a href="%s" class="attachment" rel="nofollow noopener" target="_blank">' .
  689. '<span class="invisible">%s</span>';
  690. if (strlen($styled_url) > 30) {
  691. $html .= '<span class="ellipsis">%s</span>' .
  692. '<span class="invisible">%s</span></a>';
  693. $ellipsis = substr($styled_url, 0, 30);
  694. $rest = substr($styled_url, 30);
  695. return sprintf($html, $url, $scheme, $ellipsis, $rest);
  696. } else {
  697. $html .= '%s</a>';
  698. return sprintf($html, $url, $scheme, $styled_url);
  699. }
  700. }
  701. /*
  702. * [noparse][i]italic[/i][/noparse] turns into
  703. * [noparse][ i ]italic[ /i ][/noparse],
  704. * to hide them from parser.
  705. */
  706. private static function escapeNoparseCallback($match)
  707. {
  708. $whole_match = $match[0];
  709. $captured = $match[1];
  710. $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
  711. $new_str = str_replace($captured, $spacefied, $whole_match);
  712. return $new_str;
  713. }
  714. /*
  715. * The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
  716. * now turns back and the [noparse] tags are trimed
  717. * returning [i]italic[/i]
  718. */
  719. private static function unescapeNoparseCallback($match)
  720. {
  721. $captured = $match[1];
  722. $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
  723. return $unspacefied;
  724. }
  725. /**
  726. * Returns the bracket character positions of a set of opening and closing BBCode tags, optionally skipping first
  727. * occurrences
  728. *
  729. * @param string $text Text to search
  730. * @param string $name Tag name
  731. * @param int $occurrences Number of first occurrences to skip
  732. * @return boolean|array
  733. */
  734. public static function getTagPosition($text, $name, $occurrences = 0)
  735. {
  736. if ($occurrences < 0) {
  737. $occurrences = 0;
  738. }
  739. $start_open = -1;
  740. for ($i = 0; $i <= $occurrences; $i++) {
  741. if ($start_open !== false) {
  742. $start_open = strpos($text, '[' . $name, $start_open + 1); // allow [name= type tags
  743. }
  744. }
  745. if ($start_open === false) {
  746. return false;
  747. }
  748. $start_equal = strpos($text, '=', $start_open);
  749. $start_close = strpos($text, ']', $start_open);
  750. if ($start_close === false) {
  751. return false;
  752. }
  753. $start_close++;
  754. $end_open = strpos($text, '[/' . $name . ']', $start_close);
  755. if ($end_open === false) {
  756. return false;
  757. }
  758. $res = [
  759. 'start' => [
  760. 'open' => $start_open,
  761. 'close' => $start_close
  762. ],
  763. 'end' => [
  764. 'open' => $end_open,
  765. 'close' => $end_open + strlen('[/' . $name . ']')
  766. ],
  767. ];
  768. if ($start_equal !== false) {
  769. $res['start']['equal'] = $start_equal + 1;
  770. }
  771. return $res;
  772. }
  773. /**
  774. * Performs a preg_replace within the boundaries of all named BBCode tags in a text
  775. *
  776. * @param type $pattern Preg pattern string
  777. * @param type $replace Preg replace string
  778. * @param type $name BBCode tag name
  779. * @param type $text Text to search
  780. * @return string
  781. */
  782. public static function pregReplaceInTag($pattern, $replace, $name, $text)
  783. {
  784. $occurrences = 0;
  785. $pos = self::getTagPosition($text, $name, $occurrences);
  786. while ($pos !== false && $occurrences++ < 1000) {
  787. $start = substr($text, 0, $pos['start']['open']);
  788. $subject = substr($text, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
  789. $end = substr($text, $pos['end']['close']);
  790. if ($end === false) {
  791. $end = '';
  792. }
  793. $subject = preg_replace($pattern, $replace, $subject);
  794. $text = $start . $subject . $end;
  795. $pos = self::getTagPosition($text, $name, $occurrences);
  796. }
  797. return $text;
  798. }
  799. private static function extractImagesFromItemBody($body)
  800. {
  801. $saved_image = [];
  802. $orig_body = $body;
  803. $new_body = '';
  804. $cnt = 0;
  805. $img_start = strpos($orig_body, '[img');
  806. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  807. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  808. while (($img_st_close !== false) && ($img_end !== false)) {
  809. $img_st_close++; // make it point to AFTER the closing bracket
  810. $img_end += $img_start;
  811. if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  812. // This is an embedded image
  813. $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
  814. $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]';
  815. $cnt++;
  816. } else {
  817. $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
  818. }
  819. $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
  820. if ($orig_body === false) {
  821. // in case the body ends on a closing image tag
  822. $orig_body = '';
  823. }
  824. $img_start = strpos($orig_body, '[img');
  825. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  826. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  827. }
  828. $new_body = $new_body . $orig_body;
  829. return ['body' => $new_body, 'images' => $saved_image];
  830. }
  831. private static function interpolateSavedImagesIntoItemBody($body, array $images)
  832. {
  833. $newbody = $body;
  834. $cnt = 0;
  835. foreach ($images as $image) {
  836. // We're depending on the property of 'foreach' (specified on the PHP website) that
  837. // it loops over the array starting from the first element and going sequentially
  838. // to the last element
  839. $newbody = str_replace('[$#saved_image' . $cnt . '#$]',
  840. '<img src="' . proxy_url($image) . '" alt="' . L10n::t('Image/photo') . '" />', $newbody);
  841. $cnt++;
  842. }
  843. return $newbody;
  844. }
  845. /**
  846. * Processes [share] tags
  847. *
  848. * Note: Can produce a [bookmark] tag in the output
  849. *
  850. * @brief Processes [share] tags
  851. * @param array $share preg_match_callback result array
  852. * @param bool|int $simplehtml
  853. * @return string
  854. */
  855. private static function convertShare($share, $simplehtml)
  856. {
  857. $attributes = $share[2];
  858. $author = "";
  859. preg_match("/author='(.*?)'/ism", $attributes, $matches);
  860. if (x($matches, 1)) {
  861. $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
  862. }
  863. preg_match('/author="(.*?)"/ism', $attributes, $matches);
  864. if (x($matches, 1)) {
  865. $author = $matches[1];
  866. }
  867. $profile = "";
  868. preg_match("/profile='(.*?)'/ism", $attributes, $matches);
  869. if (x($matches, 1)) {
  870. $profile = $matches[1];
  871. }
  872. preg_match('/profile="(.*?)"/ism', $attributes, $matches);
  873. if (x($matches, 1)) {
  874. $profile = $matches[1];
  875. }
  876. $avatar = "";
  877. preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
  878. if (x($matches, 1)) {
  879. $avatar = $matches[1];
  880. }
  881. preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
  882. if (x($matches, 1)) {
  883. $avatar = $matches[1];
  884. }
  885. $link = "";
  886. preg_match("/link='(.*?)'/ism", $attributes, $matches);
  887. if (x($matches, 1)) {
  888. $link = $matches[1];
  889. }
  890. preg_match('/link="(.*?)"/ism', $attributes, $matches);
  891. if (x($matches, 1)) {
  892. $link = $matches[1];
  893. }
  894. $posted = "";
  895. preg_match("/posted='(.*?)'/ism", $attributes, $matches);
  896. if (x($matches, 1)) {
  897. $posted = $matches[1];
  898. }
  899. preg_match('/posted="(.*?)"/ism', $attributes, $matches);
  900. if (x($matches, 1)) {
  901. $posted = $matches[1];
  902. }
  903. // We only call this so that a previously unknown contact can be added.
  904. // This is important for the function "Model\Contact::getDetailsByURL()".
  905. // This function then can fetch an entry from the contact table.
  906. Contact::getIdForURL($profile, 0);
  907. $data = Contact::getDetailsByURL($profile);
  908. if (x($data, "name") && x($data, "addr")) {
  909. $userid_compact = $data["name"] . " (" . $data["addr"] . ")";
  910. } else {
  911. $userid_compact = Network::getAddrFromProfileUrl($profile, $author);
  912. }
  913. if (x($data, "addr")) {
  914. $userid = $data["addr"];
  915. } else {
  916. $userid = Network::formatMention($profile, $author);
  917. }
  918. if (x($data, "name")) {
  919. $author = $data["name"];
  920. }
  921. if (x($data, "micro")) {
  922. $avatar = $data["micro"];
  923. }
  924. $preshare = trim($share[1]);
  925. if ($preshare != "") {
  926. $preshare .= "<br />";
  927. }
  928. switch ($simplehtml) {
  929. case 1:
  930. $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' <a href="' . $profile . '">' . $userid . "</a>: <br />»" . $share[3] . "«";
  931. break;
  932. case 2:
  933. $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
  934. break;
  935. case 3: // Diaspora
  936. $headline .= '<b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . $userid . ':</b><br />';
  937. $text = trim($share[1]);
  938. if ($text != "") {
  939. $text .= "<hr />";
  940. }
  941. if (stripos(normalise_link($link), 'http://twitter.com/') === 0) {
  942. $text .= $headline . '<blockquote>' . trim($share[3]) . "</blockquote><br />";
  943. if ($link != "") {
  944. $text .= '<br /><a href="' . $link . '">[l]</a>';
  945. }
  946. } else {
  947. $text .= '<br /><a href="' . $link . '">' . $link . '</a>';
  948. }
  949. break;
  950. case 4:
  951. $headline .= '<br /><b>' . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
  952. $headline .= L10n::t('<a href="%1$s" target="_blank">%2$s</a> %3$s', $link, $userid, $posted);
  953. $headline .= ":</b><br />";
  954. $text = trim($share[1]);
  955. if ($text != "") {
  956. $text .= "<hr />";
  957. }
  958. $text .= $headline . '<blockquote class="shared_content">' . trim($share[3]) . "</blockquote><br />";
  959. break;
  960. case 5:
  961. $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
  962. break;
  963. case 6: // app.net
  964. $text = $preshare . "&gt;&gt; @" . $userid_compact . ": <br />" . $share[3];
  965. break;
  966. case 7: // statusnet/GNU Social
  967. $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . " @" . $userid_compact . ": " . $share[3];
  968. break;
  969. case 8: // twitter
  970. $text = $preshare . "RT @" . $userid_compact . ": " . $share[3];
  971. break;
  972. case 9: // Google+/Facebook
  973. $text = $preshare . html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . ' ' . $userid_compact . ": <br />" . $share[3];
  974. if ($link != "") {
  975. $text .= "<br /><br />" . $link;
  976. }
  977. break;
  978. default:
  979. // Transforms quoted tweets in rich attachments to avoid nested tweets
  980. if (stripos(normalise_link($link), 'http://twitter.com/') === 0 && OEmbed::isAllowedURL($link)) {
  981. try {
  982. $oembed = OEmbed::getHTML($link, $preshare);
  983. } catch (Exception $e) {
  984. $oembed = sprintf('[bookmark=%s]%s[/bookmark]', $link, $preshare);
  985. }
  986. $text = $preshare . $oembed;
  987. } else {
  988. $text = trim($share[1]) . "\n";
  989. $avatar = proxy_url($avatar, false, PROXY_SIZE_THUMB);
  990. $tpl = get_markup_template('shared_content.tpl');
  991. $text .= replace_macros($tpl, [
  992. '$profile' => $profile,
  993. '$avatar' => $avatar,
  994. '$author' => $author,
  995. '$link' => $link,
  996. '$posted' => $posted,
  997. '$content' => trim($share[3])
  998. ]);
  999. }
  1000. break;
  1001. }
  1002. return $text;
  1003. }
  1004. private static function removePictureLinksCallback($match)
  1005. {
  1006. $text = Cache::get($match[1]);
  1007. if (is_null($text)) {
  1008. $a = get_app();
  1009. $stamp1 = microtime(true);
  1010. $ch = @curl_init($match[1]);
  1011. @curl_setopt($ch, CURLOPT_NOBODY, true);
  1012. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1013. @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  1014. @curl_exec($ch);
  1015. $curl_info = @curl_getinfo($ch);
  1016. $a->save_timestamp($stamp1, "network");
  1017. if (substr($curl_info["content_type"], 0, 6) == "image/") {
  1018. $text = "[url=" . $match[1] . "]" . $match[1] . "[/url]";
  1019. } else {
  1020. $text = "[url=" . $match[2] . "]" . $match[2] . "[/url]";
  1021. // if its not a picture then look if its a page that contains a picture link
  1022. $body = Network::fetchUrl($match[1]);
  1023. $doc = new DOMDocument();
  1024. @$doc->loadHTML($body);
  1025. $xpath = new DomXPath($doc);
  1026. $list = $xpath->query("//meta[@name]");
  1027. foreach ($list as $node) {
  1028. $attr = [];
  1029. if ($node->attributes->length) {
  1030. foreach ($node->attributes as $attribute) {
  1031. $attr[$attribute->name] = $attribute->value;
  1032. }
  1033. }
  1034. if (strtolower($attr["name"]) == "twitter:image") {
  1035. $text = "[url=" . $attr["content"] . "]" . $attr["content"] . "[/url]";
  1036. }
  1037. }
  1038. }
  1039. Cache::set($match[1], $text);
  1040. }
  1041. return $text;
  1042. }
  1043. private static function expandLinksCallback($match)
  1044. {
  1045. if (($match[3] == "") || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
  1046. return ($match[1] . "[url]" . $match[2] . "[/url]");
  1047. } else {
  1048. return ($match[1] . $match[3] . " [url]" . $match[2] . "[/url]");
  1049. }
  1050. }
  1051. private static function cleanPictureLinksCallback($match)
  1052. {
  1053. $text = Cache::get($match[1]);
  1054. if (is_null($text)) {
  1055. $a = get_app();
  1056. $stamp1 = microtime(true);
  1057. $ch = @curl_init($match[1]);
  1058. @curl_setopt($ch, CURLOPT_NOBODY, true);
  1059. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1060. @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  1061. @curl_exec($ch);
  1062. $curl_info = @curl_getinfo($ch);
  1063. $a->save_timestamp($stamp1, "network");
  1064. // if its a link to a picture then embed this picture
  1065. if (substr($curl_info["content_type"], 0, 6) == "image/") {
  1066. $text = "[img]" . $match[1] . "[/img]";
  1067. } else {
  1068. $text = "[img]" . $match[2] . "[/img]";
  1069. // if its not a picture then look if its a page that contains a picture link
  1070. $body = Network::fetchUrl($match[1]);
  1071. $doc = new DOMDocument();
  1072. @$doc->loadHTML($body);
  1073. $xpath = new DomXPath($doc);
  1074. $list = $xpath->query("//meta[@name]");
  1075. foreach ($list as $node) {
  1076. $attr = [];
  1077. if ($node->attributes->length) {
  1078. foreach ($node->attributes as $attribute) {
  1079. $attr[$attribute->name] = $attribute->value;
  1080. }
  1081. }
  1082. if (strtolower($attr["name"]) == "twitter:image") {
  1083. $text = "[img]" . $attr["content"] . "[/img]";
  1084. }
  1085. }
  1086. }
  1087. Cache::set($match[1], $text);
  1088. }
  1089. return $text;
  1090. }
  1091. public static function cleanPictureLinks($text)
  1092. {
  1093. $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'self::cleanPictureLinksCallback', $text);
  1094. return $return;
  1095. }
  1096. private static function textHighlightCallback($match)
  1097. {
  1098. if (in_array(strtolower($match[1]),
  1099. ['php', 'css', 'mysql', 'sql', 'abap', 'diff', 'html', 'perl', 'ruby',
  1100. 'vbscript', 'avrc', 'dtd', 'java', 'xml', 'cpp', 'python', 'javascript', 'js', 'sh'])
  1101. ) {
  1102. return text_highlight($match[2], strtolower($match[1]));
  1103. }
  1104. return $match[0];
  1105. }
  1106. /**
  1107. * @brief Converts a BBCode message to HTML message
  1108. *
  1109. * BBcode 2 HTML was written by WAY2WEB.net
  1110. * extended to work with Mistpark/Friendica - Mike Macgirvin
  1111. *
  1112. * Simple HTML values meaning:
  1113. * - 0: Friendica display
  1114. * - 1: Unused
  1115. * - 2: Used for Facebook, Google+, Windows Phone push, Friendica API
  1116. * - 3: Used before converting to Markdown in bb2diaspora.php
  1117. * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr
  1118. * - 5: Unused
  1119. * - 6: Used for Appnet
  1120. * - 7: Used for dfrn, OStatus
  1121. * - 8: Used for WP backlink text setting
  1122. *
  1123. * @param string $text
  1124. * @param bool $preserve_nl
  1125. * @param bool $try_oembed
  1126. * @param int $simple_html
  1127. * @param bool $for_plaintext
  1128. * @return string
  1129. */
  1130. public static function convert($text, $preserve_nl = false, $try_oembed = true, $simple_html = false, $for_plaintext = false)
  1131. {
  1132. $a = get_app();
  1133. /*
  1134. * preg_match_callback function to replace potential Oembed tags with Oembed content
  1135. *
  1136. * $match[0] = [tag]$url[/tag] or [tag=$url]$title[/tag]
  1137. * $match[1] = $url
  1138. * $match[2] = $title or absent
  1139. */
  1140. $try_oembed_callback = function ($match)
  1141. {
  1142. $url = $match[1];
  1143. $title = defaults($match, 2, null);
  1144. try {
  1145. $return = OEmbed::getHTML($url, $title);
  1146. } catch (Exception $ex) {
  1147. $return = $match[0];
  1148. }
  1149. return $return;
  1150. };
  1151. // Hide all [noparse] contained bbtags by spacefying them
  1152. // POSSIBLE BUG --> Will the 'preg' functions crash if there's an embedded image?
  1153. $text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'self::escapeNoparseCallback', $text);
  1154. $text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'self::escapeNoparseCallback', $text);
  1155. $text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'self::escapeNoparseCallback', $text);
  1156. // Remove the abstract element. It is a non visible element.
  1157. $text = self::stripAbstract($text);
  1158. // Move all spaces out of the tags
  1159. $text = preg_replace("/\[(\w*)\](\s*)/ism", '$2[$1]', $text);
  1160. $text = preg_replace("/(\s*)\[\/(\w*)\]/ism", '[/$2]$1', $text);
  1161. // Extract the private images which use data urls since preg has issues with
  1162. // large data sizes. Stash them away while we do bbcode conversion, and then put them back
  1163. // in after we've done all the regex matching. We cannot use any preg functions to do this.
  1164. $extracted = self::extractImagesFromItemBody($text);
  1165. $text = $extracted['body'];
  1166. $saved_image = $extracted['images'];
  1167. // If we find any event code, turn it into an event.
  1168. // After we're finished processing the bbcode we'll
  1169. // replace all of the event code with a reformatted version.
  1170. $ev = bbtoevent($text);
  1171. // Replace any html brackets with HTML Entities to prevent executing HTML or script
  1172. // Don't use strip_tags here because it breaks [url] search by replacing & with amp
  1173. $text = str_replace("<", "&lt;", $text);
  1174. $text = str_replace(">", "&gt;", $text);
  1175. // remove some newlines before the general conversion
  1176. $text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "[share$1]$2[/share]", $text);
  1177. $text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "[quote$1]$2[/quote]", $text);
  1178. $text = preg_replace("/\n\[code\]/ism", "[code]", $text);
  1179. $text = preg_replace("/\[\/code\]\n/ism", "[/code]", $text);
  1180. // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
  1181. if (!$try_oembed) {
  1182. $text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1$2]$3[/share]", $text);
  1183. }
  1184. // Check for [code] text here, before the linefeeds are messed with.
  1185. // The highlighter will unescape and re-escape the content.
  1186. if (strpos($text, '[code=') !== false) {
  1187. $text = preg_replace_callback("/\[code=(.*?)\](.*?)\[\/code\]/ism", 'self::textHighlightCallback', $text);
  1188. }
  1189. // Convert new line chars to html <br /> tags
  1190. // nlbr seems to be hopelessly messed up
  1191. // $Text = nl2br($Text);
  1192. // We'll emulate it.
  1193. $text = trim($text);
  1194. $text = str_replace("\r\n", "\n", $text);
  1195. // removing multiplicated newlines
  1196. if (Config::get("system", "remove_multiplicated_lines")) {
  1197. $search = ["\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[ul]", "[/ul]\n", "\n\n[share ", "[/attachment]\n",
  1198. "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n"];
  1199. $replace = ["\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ", "[/attachment]",
  1200. "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]"];
  1201. do {
  1202. $oldtext = $text;
  1203. $text = str_replace($search, $replace, $text);
  1204. } while ($oldtext != $text);
  1205. }
  1206. // Set up the parameters for a URL search string
  1207. $URLSearchString = "^\[\]";
  1208. // Set up the parameters for a MAIL search string
  1209. $MAILSearchString = $URLSearchString;
  1210. // if the HTML is used to generate plain text, then don't do this search, but replace all URL of that kind to text
  1211. if (!$for_plaintext) {
  1212. // Autolink feature (thanks to http://code.seebz.net/p/autolink-php/)
  1213. // Currently disabled, since the function is too greedy
  1214. // $autolink_regex = "`([^\]\=\"']|^)(https?\://[^\s<]+[^\s<\.\)])`ism";
  1215. $autolink_regex = "/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism";
  1216. $text = preg_replace($autolink_regex, '$1[url]$2[/url]', $text);
  1217. if ($simple_html == 7) {
  1218. $text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'self::convertUrlForMastodonCallback', $text);
  1219. $text = preg_replace_callback("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", 'self::convertUrlForMastodonCallback', $text);
  1220. }
  1221. } else {
  1222. $text = preg_replace("(\[url\]([$URLSearchString]*)\[\/url\])ism", " $1 ", $text);
  1223. $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'self::removePictureLinksCallback', $text);
  1224. }
  1225. // Handle attached links or videos
  1226. $text = self::convertAttachment($text, $simple_html, $try_oembed);
  1227. $text = str_replace(["\r","\n"], ['<br />', '<br />'], $text);
  1228. if ($preserve_nl) {
  1229. $text = str_replace(["\n", "\r"], ['', ''], $text);
  1230. }
  1231. // Remove all hashtag addresses
  1232. if ((!$try_oembed || $simple_html) && !in_array($simple_html, [3, 7])) {
  1233. $text = preg_replace("/([#@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
  1234. } elseif ($simple_html == 3) {
  1235. // The ! is converted to @ since Diaspora only understands the @
  1236. $text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1237. '@<a href="$2">$3</a>',
  1238. $text);
  1239. } elseif ($simple_html == 7) {
  1240. $text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1241. '$1<span class="vcard"><a href="$2" class="url" title="$3"><span class="fn nickname mention">$3</span></a></span>',
  1242. $text);
  1243. } elseif (!$simple_html) {
  1244. $text = preg_replace("/([@!])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1245. '$1<a href="$2" class="userinfo mention" title="$3">$3</a>',
  1246. $text);
  1247. }
  1248. // Bookmarks in red - will be converted to bookmarks in friendica
  1249. $text = preg_replace("/#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $text);
  1250. $text = preg_replace("/#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $text);
  1251. $text = preg_replace("/#\[url\=[$URLSearchString]*\]\^\[\/url\]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i",
  1252. "[bookmark=$1]$2[/bookmark]", $text);
  1253. if (in_array($simple_html, [2, 6, 7, 8, 9])) {
  1254. $text = preg_replace_callback("/([^#@!])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", "self::expandLinksCallback", $text);
  1255. //$Text = preg_replace("/[^#@!]\[url\=([^\]]*)\](.*?)\[\/url\]/ism", ' $2 [url]$1[/url]', $Text);
  1256. $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", ' $2 [url]$1[/url]',$text);
  1257. }
  1258. if ($simple_html == 5) {
  1259. $text = preg_replace("/[^#@!]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url]$1[/url]', $text);
  1260. }
  1261. // Perform URL Search
  1262. if ($try_oembed) {
  1263. $text = preg_replace_callback("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $try_oembed_callback, $text);
  1264. }
  1265. if ($simple_html == 5) {
  1266. $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url]$1[/url]', $text);
  1267. } else {
  1268. $text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $text);
  1269. }
  1270. // Handle Diaspora posts
  1271. $text = preg_replace_callback(
  1272. "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
  1273. function ($match) {
  1274. return "[url=" . System::baseUrl() . "/display/" . $match[1] . "]" . $match[2] . "[/url]";
  1275. }, $text
  1276. );
  1277. // Server independent link to posts and comments
  1278. // See issue: https://github.com/diaspora/diaspora_federation/issues/75
  1279. $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
  1280. $text = preg_replace($expression, System::baseUrl()."/display/$1", $text);
  1281. $text = preg_replace("/([#])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1282. '$1<a href="' . System::baseUrl() . '/search?tag=$3" class="tag" title="$3">$3</a>', $text);
  1283. $text = preg_replace("/\[url\=([$URLSearchString]*)\]#(.*?)\[\/url\]/ism",
  1284. '#<a href="' . System::baseUrl() . '/search?tag=$2" class="tag" title="$2">$2</a>', $text);
  1285. $text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$1</a>', $text);
  1286. $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $text);
  1287. //$Text = preg_replace("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
  1288. // Red compatibility, though the link can't be authenticated on Friendica
  1289. $text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<a href="$1" target="_blank">$2</a>', $text);
  1290. // we may need to restrict this further if it picks up too many strays
  1291. // link acct:user@host to a webfinger profile redirector
  1292. $text = preg_replace('/acct:([^@]+)@((?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63})/', '<a href="' . System::baseUrl() . '/acctlink?addr=$1@$2" target="extlink">acct:$1@$2</a>', $text);
  1293. // Perform MAIL Search
  1294. $text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $text);
  1295. $text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $text);
  1296. // leave open the posibility of [map=something]
  1297. // this is replaced in prepare_body() which has knowledge of the item location
  1298. if (strpos($text, '[/map]') !== false) {
  1299. $text = preg_replace_callback(
  1300. "/\[map\](.*?)\[\/map\]/ism",
  1301. function ($match) {
  1302. // the extra space in the following line is intentional
  1303. // Whyyy? - @MrPetovan
  1304. return str_replace($match[0], '<div class="map" >' . Map::byLocation($match[1]) . '</div>', $match[0]);
  1305. },
  1306. $text
  1307. );
  1308. }
  1309. if (strpos($text, '[map=') !== false) {
  1310. $text = preg_replace_callback(
  1311. "/\[map=(.*?)\]/ism",
  1312. function ($match) {
  1313. // the extra space in the following line is intentional
  1314. // Whyyy? - @MrPetovan
  1315. return str_replace($match[0], '<div class="map" >' . Map::byCoordinates(str_replace('/', ' ', $match[1])) . '</div>', $match[0]);
  1316. },
  1317. $text
  1318. );
  1319. }
  1320. if (strpos($text, '[map]') !== false) {
  1321. $text = preg_replace("/\[map\]/", '<div class="map"></div>', $text);
  1322. }
  1323. // Check for headers
  1324. $text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '<h1>$1</h1>', $text);
  1325. $text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '<h2>$1</h2>', $text);
  1326. $text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '<h3>$1</h3>', $text);
  1327. $text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '<h4>$1</h4>', $text);
  1328. $text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '<h5>$1</h5>', $text);
  1329. $text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '<h6>$1</h6>', $text);
  1330. // Check for paragraph
  1331. $text = preg_replace("(\[p\](.*?)\[\/p\])ism", '<p>$1</p>', $text);
  1332. // Check for bold text
  1333. $text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $text);
  1334. // Check for Italics text
  1335. $text = preg_replace("(\[i\](.*?)\[\/i\])ism", '<em>$1</em>', $text);
  1336. // Check for Underline text
  1337. $text = preg_replace("(\[u\](.*?)\[\/u\])ism", '<u>$1</u>', $text);
  1338. // Check for strike-through text
  1339. $text = preg_replace("(\[s\](.*?)\[\/s\])ism", '<strike>$1</strike>', $text);
  1340. // Check for over-line text
  1341. $text = preg_replace("(\[o\](.*?)\[\/o\])ism", '<span class="overline">$1</span>', $text);
  1342. // Check for colored text
  1343. $text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "<span style=\"color: $1;\">$2</span>", $text);
  1344. // Check for sized text
  1345. // [size=50] --> font-size: 50px (with the unit).
  1346. $text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1px; line-height: initial;\">$2</span>", $text);
  1347. $text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1; line-height: initial;\">$2</span>", $text);
  1348. // Check for centered text
  1349. $text = preg_replace("(\[center\](.*?)\[\/center\])ism", "<div style=\"text-align:center;\">$1</div>", $text);
  1350. // Check for list text
  1351. $text = str_replace("[*]", "<li>", $text);
  1352. // Check for style sheet commands
  1353. $text = preg_replace_callback(
  1354. "(\[style=(.*?)\](.*?)\[\/style\])ism",
  1355. function ($match) {
  1356. return "<span style=\"" . self::cleanCss($match[1]) . ";\">" . $match[2] . "</span>";
  1357. },
  1358. $text
  1359. );
  1360. // Check for CSS classes
  1361. $text = preg_replace_callback(
  1362. "(\[class=(.*?)\](.*?)\[\/class\])ism",
  1363. function ($match) {
  1364. return "<span class=\"" . self::cleanCss($match[1]) . "\">" . $match[2] . "</span>";
  1365. },
  1366. $text
  1367. );
  1368. // handle nested lists
  1369. $endlessloop = 0;
  1370. while ((((strpos($text, "[/list]") !== false) && (strpos($text, "[list") !== false)) ||
  1371. ((strpos($text, "[/ol]") !== false) && (strpos($text, "[ol]") !== false)) ||
  1372. ((strpos($text, "[/ul]") !== false) && (strpos($text, "[ul]") !== false)) ||
  1373. ((strpos($text, "[/li]") !== false) && (strpos($text, "[li]") !== false))) && (++$endlessloop < 20)) {
  1374. $text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $text);
  1375. $text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>', $text);
  1376. $text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $text);
  1377. $text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>', $text);
  1378. $text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>', $text);
  1379. $text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>', $text);
  1380. $text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>', $text);
  1381. $text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $text);
  1382. $text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $text);
  1383. $text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $text);
  1384. }
  1385. $text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $text);
  1386. $text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $text);
  1387. $text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $text);
  1388. $text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>', $text);
  1389. $text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>', $text);
  1390. $text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>', $text);
  1391. $text = str_replace('[hr]', '<hr />', $text);
  1392. // This is actually executed in prepare_body()
  1393. $text = str_replace('[nosmile]', '', $text);
  1394. // Check for font change text
  1395. $text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "<span style=\"font-family: $1;\">$2</span>", $text);
  1396. // Declare the format for [code] layout
  1397. $CodeLayout = '<code>$1</code>';
  1398. // Check for [code] text
  1399. $text = preg_replace("/\[code\](.*?)\[\/code\]/ism", "$CodeLayout", $text);
  1400. // Declare the format for [spoiler] layout
  1401. $SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
  1402. // Check for [spoiler] text
  1403. // handle nested quotes
  1404. $endlessloop = 0;
  1405. while ((strpos($text, "[/spoiler]") !== false) && (strpos($text, "[spoiler]") !== false) && (++$endlessloop < 20)) {
  1406. $text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $text);
  1407. }
  1408. // Check for [spoiler=Author] text
  1409. $t_wrote = L10n::t('$1 wrote:');
  1410. // handle nested quotes
  1411. $endlessloop = 0;
  1412. while ((strpos($text, "[/spoiler]")!== false) && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
  1413. $text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
  1414. "<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
  1415. $text);
  1416. }
  1417. // Declare the format for [quote] layout
  1418. $QuoteLayout = '<blockquote>$1</blockquote>';
  1419. // Check for [quote] text
  1420. // handle nested quotes
  1421. $endlessloop = 0;
  1422. while ((strpos($text, "[/quote]") !== false) && (strpos($text, "[quote]") !== false) && (++$endlessloop < 20)) {
  1423. $text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $text);
  1424. }
  1425. // Check for [quote=Author] text
  1426. $t_wrote = L10n::t('$1 wrote:');
  1427. // handle nested quotes
  1428. $endlessloop = 0;
  1429. while ((strpos($text, "[/quote]")!== false) && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) {
  1430. $text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
  1431. "<br /><strong class=".'"author"'.">" . $t_wrote . "</strong><blockquote>$2</blockquote>",
  1432. $text);
  1433. }
  1434. // [img=widthxheight]image source[/img]
  1435. $text = preg_replace_callback(
  1436. "/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism",
  1437. function ($matches) {
  1438. if (strpos($matches[3], "data:image/") === 0) {
  1439. return $matches[0];
  1440. }
  1441. $matches[3] = proxy_url($matches[3]);
  1442. return "[img=" . $matches[1] . "x" . $matches[2] . "]" . $matches[3] . "[/img]";
  1443. },
  1444. $text
  1445. );
  1446. $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $text);
  1447. $text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $text);
  1448. // Images
  1449. // [img]pathtoimage[/img]
  1450. $text = preg_replace_callback(
  1451. "/\[img\](.*?)\[\/img\]/ism",
  1452. function ($matches) {
  1453. if (strpos($matches[1], "data:image/") === 0) {
  1454. return $matches[0];
  1455. }
  1456. $matches[1] = proxy_url($matches[1]);
  1457. return "[img]" . $matches[1] . "[/img]";
  1458. },
  1459. $text
  1460. );
  1461. $text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . L10n::t('Image/photo') . '" />', $text);
  1462. $text = preg_replace("/\[zmg\](.*?)\[\/zmg\]/ism", '<img src="$1" alt="' . L10n::t('Image/photo') . '" />', $text);
  1463. // Shared content
  1464. $text = preg_replace_callback("/(.*?)\[share(.*?)\](.*?)\[\/share\]/ism",
  1465. function ($match) use ($simple_html) {
  1466. return self::convertShare($match, $simple_html);
  1467. }, $text);
  1468. $text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism", '<br/><img src="' .System::baseUrl() . '/images/lock_icon.gif" alt="' . L10n::t('Encrypted content') . '" title="' . L10n::t('Encrypted content') . '" /><br />', $text);
  1469. $text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism", '<br/><img src="' .System::baseUrl() . '/images/lock_icon.gif" alt="' . L10n::t('Encrypted content') . '" title="' . '$1' . ' ' . L10n::t('Encrypted content') . '" /><br />', $text);
  1470. //$Text = preg_replace("/\[crypt=(.*?)\](.*?)\[\/crypt\]/ism", '<br/><img src="' .System::baseUrl() . '/images/lock_icon.gif" alt="' . L10n::t('Encrypted content') . '" title="' . '$1' . ' ' . L10n::t('Encrypted content') . '" /><br />', $Text);
  1471. // Try to Oembed
  1472. if ($try_oembed) {
  1473. $text = preg_replace("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4))\[\/video\]/ism", '<video src="$1" controls="controls" width="' . $a->videowidth . '" height="' . $a->videoheight . '" loop="true"><a href="$1">$1</a></video>', $text);
  1474. $text = preg_replace("/\[audio\](.*?\.(ogg|ogv|oga|ogm|webm|mp4|mp3))\[\/audio\]/ism", '<audio src="$1" controls="controls"><a href="$1">$1</a></audio>', $text);
  1475. $text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", $try_oembed_callback, $text);
  1476. $text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", $try_oembed_callback, $text);
  1477. } else {
  1478. $text = preg_replace("/\[video\](.*?)\[\/video\]/",
  1479. '<a href="$1" target="_blank">$1</a>', $text);
  1480. $text = preg_replace("/\[audio\](.*?)\[\/audio\]/",
  1481. '<a href="$1" target="_blank">$1</a>', $text);
  1482. }
  1483. // html5 video and audio
  1484. if ($try_oembed) {
  1485. $text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<iframe src="$1" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></iframe>', $text);
  1486. } else {
  1487. $text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $text);
  1488. }
  1489. // Youtube extensions
  1490. if ($try_oembed) {
  1491. $text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", $try_oembed_callback, $text);
  1492. $text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", $try_oembed_callback, $text);
  1493. $text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism", $try_oembed_callback, $text);
  1494. }
  1495. $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
  1496. $text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
  1497. $text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $text);
  1498. if ($try_oembed) {
  1499. $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="https://www.youtube.com/embed/$1" frameborder="0" ></iframe>', $text);
  1500. } else {
  1501. $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
  1502. '<a href="https://www.youtube.com/watch?v=$1" target="_blank">https://www.youtube.com/watch?v=$1</a>', $text);
  1503. }
  1504. if ($try_oembed) {
  1505. $text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism", $try_oembed_callback, $text);
  1506. $text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism", $try_oembed_callback, $text);
  1507. }
  1508. $text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $text);
  1509. $text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $text);
  1510. if ($try_oembed) {
  1511. $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '<iframe width="' . $a->videowidth . '" height="' . $a->videoheight . '" src="https://player.vimeo.com/video/$1" frameborder="0" ></iframe>', $text);
  1512. } else {
  1513. $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
  1514. '<a href="https://vimeo.com/$1" target="_blank">https://vimeo.com/$1</a>', $text);
  1515. }
  1516. // oembed tag
  1517. $text = OEmbed::BBCode2HTML($text);
  1518. // Avoid triple linefeeds through oembed
  1519. $text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $text);
  1520. // If we found an event earlier, strip out all the event code and replace with a reformatted version.
  1521. // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
  1522. // Summary (e.g. title) is required, earlier revisions only required description (in addition to
  1523. // start which is always required). Allow desc with a missing summary for compatibility.
  1524. if ((x($ev, 'desc') || x($ev, 'summary')) && x($ev, 'start')) {
  1525. $sub = format_event_html($ev, $simple_html);
  1526. $text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism", '', $text);
  1527. $text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism", '', $text);
  1528. $text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism", $sub, $text);
  1529. $text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism", '', $text);
  1530. $text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism", '', $text);
  1531. $text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/ism", '', $text);
  1532. $text = preg_replace("/\[event\-id\](.*?)\[\/event\-id\]/ism", '', $text);
  1533. }
  1534. // Replace non graphical smilies for external posts
  1535. if ($simple_html) {
  1536. $text = Smilies::replace($text, false, true);
  1537. }
  1538. // Replace inline code blocks
  1539. $text = preg_replace_callback("|(?!<br[^>]*>)<code>([^<]*)</code>(?!<br[^>]*>)|ism",
  1540. function ($match) use ($simple_html) {
  1541. $return = '<key>' . $match[1] . '</key>';
  1542. // Use <code> for Diaspora inline code blocks
  1543. if ($simple_html === 3) {
  1544. $return = '<code>' . $match[1] . '</code>';
  1545. }
  1546. return $return;
  1547. }
  1548. , $text);
  1549. // Unhide all [noparse] contained bbtags unspacefying them
  1550. // and triming the [noparse] tag.
  1551. $text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'self::unescapeNoparseCallback', $text);
  1552. $text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'self::unescapeNoparseCallback', $text);
  1553. $text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'self::unescapeNoparseCallback', $text);
  1554. $text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/', '&$1;', $text);
  1555. $text = preg_replace('/\&\#039\;/', '\'', $text);
  1556. $text = preg_replace('/\&quot\;/', '"', $text);
  1557. // fix any escaped ampersands that may have been converted into links
  1558. $text = preg_replace('/\<([^>]*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism', '<$1$2=$3&$4>', $text);
  1559. // sanitizes src attributes (http and redir URLs for displaying in a web page, cid used for inline images in emails)
  1560. $allowed_src_protocols = ['http', 'redir', 'cid'];
  1561. $text = preg_replace('#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
  1562. '<$1$2=""$4 data-original-src="$3" class="invalid-src" title="' . L10n::t('Invalid source protocol') . '">', $text);
  1563. // sanitize href attributes (only whitelisted protocols URLs)
  1564. // default value for backward compatibility
  1565. $allowed_link_protocols = Config::get('system', 'allowed_link_protocols', ['ftp', 'mailto', 'gopher', 'cid']);
  1566. // Always allowed protocol even if config isn't set or not including it
  1567. $allowed_link_protocols[] = 'http';
  1568. $allowed_link_protocols[] = 'redir/';
  1569. $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
  1570. $text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 data-original-href="$3" class="invalid-href" title="' . L10n::t('Invalid link protocol') . '">', $text);
  1571. if ($saved_image) {
  1572. $text = self::interpolateSavedImagesIntoItemBody($text, $saved_image);
  1573. }
  1574. // Clean up the HTML by loading and saving the HTML with the DOM.
  1575. // Bad structured html can break a whole page.
  1576. // For performance reasons do it only with ativated item cache or at export.
  1577. if (!$try_oembed || (get_itemcachepath() != "")) {
  1578. $doc = new DOMDocument();
  1579. $doc->preserveWhiteSpace = false;
  1580. $text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
  1581. $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
  1582. $encoding = '<?xml encoding="UTF-8">';
  1583. @$doc->loadHTML($encoding.$doctype."<html><body>".$text."</body></html>");
  1584. $doc->encoding = 'UTF-8';
  1585. $text = $doc->saveHTML();
  1586. $text = str_replace(["<html><body>", "</body></html>", $doctype, $encoding], ["", "", "", ""], $text);
  1587. $text = str_replace('<br></li>', '</li>', $text);
  1588. //$Text = mb_convert_encoding($Text, "UTF-8", 'HTML-ENTITIES');
  1589. }
  1590. // Clean up some useless linebreaks in lists
  1591. //$Text = str_replace('<br /><ul', '<ul ', $Text);
  1592. //$Text = str_replace('</ul><br />', '</ul>', $Text);
  1593. //$Text = str_replace('</li><br />', '</li>', $Text);
  1594. //$Text = str_replace('<br /><li>', '<li>', $Text);
  1595. //$Text = str_replace('<br /><ul', '<ul ', $Text);
  1596. Addon::callHooks('bbcode', $text);
  1597. return trim($text);
  1598. }
  1599. /**
  1600. * @brief Strips the "abstract" tag from the provided text
  1601. *
  1602. * @param string $text The text with BBCode
  1603. * @return string The same text - but without "abstract" element
  1604. */
  1605. public static function stripAbstract($text)
  1606. {
  1607. $text = preg_replace("/[\s|\n]*\[abstract\].*?\[\/abstract\][\s|\n]*/ism", '', $text);
  1608. $text = preg_replace("/[\s|\n]*\[abstract=.*?\].*?\[\/abstract][\s|\n]*/ism", '', $text);
  1609. return $text;
  1610. }
  1611. /**
  1612. * @brief Returns the value of the "abstract" element
  1613. *
  1614. * @param string $text The text that maybe contains the element
  1615. * @param string $addon The addon for which the abstract is meant for
  1616. * @return string The abstract
  1617. */
  1618. private static function getAbstract($text, $addon = "")
  1619. {
  1620. $abstract = "";
  1621. $abstracts = [];
  1622. $addon = strtolower($addon);
  1623. if (preg_match_all("/\[abstract=(.*?)\](.*?)\[\/abstract\]/ism", $text, $results, PREG_SET_ORDER)) {
  1624. foreach ($results AS $result) {
  1625. $abstracts[strtolower($result[1])] = $result[2];
  1626. }
  1627. }
  1628. if (isset($abstracts[$addon])) {
  1629. $abstract = $abstracts[$addon];
  1630. }
  1631. if ($abstract == "" && preg_match("/\[abstract\](.*?)\[\/abstract\]/ism", $text, $result)) {
  1632. $abstract = $result[1];
  1633. }
  1634. return $abstract;
  1635. }
  1636. }