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.

1390 lines
49KB

  1. <?php
  2. use Friendica\App;
  3. use Friendica\Core\Config;
  4. require_once 'include/oembed.php';
  5. require_once 'include/event.php';
  6. require_once 'include/map.php';
  7. require_once 'mod/proxy.php';
  8. require_once 'include/Contact.php';
  9. require_once 'include/plaintext.php';
  10. function bb_PictureCacheExt($matches) {
  11. if (strpos($matches[3], "data:image/") === 0) {
  12. return $matches[0];
  13. }
  14. $matches[3] = proxy_url($matches[3]);
  15. return "[img=" . $matches[1] . "x" . $matches[2] . "]" . $matches[3] . "[/img]";
  16. }
  17. function bb_PictureCache($matches) {
  18. if (strpos($matches[1], "data:image/") === 0) {
  19. return $matches[0];
  20. }
  21. $matches[1] = proxy_url($matches[1]);
  22. return "[img]" . $matches[1] . "[/img]";
  23. }
  24. function bb_map_coords($match) {
  25. // the extra space in the following line is intentional
  26. return str_replace($match[0], '<div class="map" >' . generate_map(str_replace('/', ' ', $match[1])) . '</div>', $match[0]);
  27. }
  28. function bb_map_location($match) {
  29. // the extra space in the following line is intentional
  30. return str_replace($match[0], '<div class="map" >' . generate_named_map($match[1]) . '</div>', $match[0]);
  31. }
  32. function bb_attachment($Text, $simplehtml = false, $tryoembed = true) {
  33. $data = get_attachment_data($Text);
  34. if (!$data) {
  35. return $Text;
  36. }
  37. if (isset($data["title"])) {
  38. $data["title"] = strip_tags($data["title"]);
  39. $data["title"] = str_replace(array("http://", "https://"), "", $data["title"]);
  40. }
  41. if (((strpos($data["text"], "[img=") !== false) || (strpos($data["text"], "[img]") !== false)) && ($data["image"] != "")) {
  42. $data["preview"] = $data["image"];
  43. $data["image"] = "";
  44. }
  45. if ($simplehtml == 7) {
  46. $text = style_url_for_mastodon($data["url"]);
  47. } elseif (($simplehtml != 4) && ($simplehtml != 0)) {
  48. $text = sprintf('<a href="%s" target="_blank">%s</a><br>', $data["url"], $data["title"]);
  49. } else {
  50. $text = sprintf('<span class="type-%s">', $data["type"]);
  51. $bookmark = array(sprintf('[bookmark=%s]%s[/bookmark]', $data["url"], $data["title"]), $data["url"], $data["title"]);
  52. if ($tryoembed) {
  53. $oembed = tryoembed($bookmark);
  54. } else {
  55. $oembed = $bookmark[0];
  56. }
  57. if (strstr(strtolower($oembed), "<iframe ")) {
  58. $text = $oembed;
  59. } else {
  60. if (($data["image"] != "") && !strstr(strtolower($oembed), "<img ")) {
  61. $text .= 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"]);
  62. } elseif (($data["preview"] != "") && !strstr(strtolower($oembed), "<img ")) {
  63. $text .= 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"]);
  64. }
  65. if (($data["type"] == "photo") && ($data["url"] != "") && ($data["image"] != "")) {
  66. $text .= sprintf('<a href="%s" target="_blank"><img src="%s" alt="" title="%s" class="attachment-image" /></a>', $data["url"], proxy_url($data["image"]), $data["title"]);
  67. } else {
  68. $text .= $oembed;
  69. }
  70. if (trim($data["description"]) != "") {
  71. $text .= sprintf('<blockquote>%s</blockquote></span>', trim(bbcode($data["description"])));
  72. }
  73. }
  74. }
  75. return trim($data["text"].' '.$text.' '.$data["after"]);
  76. }
  77. function bb_remove_share_information($Text, $plaintext = false, $nolink = false) {
  78. $data = get_attachment_data($Text);
  79. if (!$data) {
  80. return $Text;
  81. } elseif ($nolink) {
  82. return $data["text"] . $data["after"];
  83. }
  84. $title = htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false);
  85. $text = htmlentities($data["text"], ENT_QUOTES, 'UTF-8', false);
  86. if ($plaintext || (($title != "") && strstr($text, $title))) {
  87. $data["title"] = $data["url"];
  88. } elseif (($text != "") && strstr($title, $text)) {
  89. $data["text"] = $data["title"];
  90. $data["title"] = $data["url"];
  91. }
  92. if (($data["text"] == "") && ($data["title"] != "") && ($data["url"] == "")) {
  93. return $data["title"] . $data["after"];
  94. }
  95. // If the link already is included in the post, don't add it again
  96. if (($data["url"] != "") && strpos($data["text"], $data["url"])) {
  97. return $data["text"] . $data["after"];
  98. }
  99. $text = $data["text"];
  100. if (($data["url"] != "") && ($data["title"] != "")) {
  101. $text .= "\n[url=" . $data["url"] . "]" . $data["title"] . "[/url]";
  102. } elseif (($data["url"] != "")) {
  103. $text .= "\n" . $data["url"];
  104. }
  105. return $text . "\n" . $data["after"];
  106. }
  107. function bb_cleanstyle($st) {
  108. return "<span style=\"" . cleancss($st[1]) . ";\">" . $st[2] . "</span>";
  109. }
  110. function bb_cleanclass($st) {
  111. return "<span class=\"" . cleancss($st[1]) . "\">" . $st[2] . "</span>";
  112. }
  113. function cleancss($input) {
  114. $cleaned = "";
  115. $input = strtolower($input);
  116. for ($i = 0; $i < strlen($input); $i++) {
  117. $char = substr($input, $i, 1);
  118. if (($char >= "a") && ($char <= "z")) {
  119. $cleaned .= $char;
  120. }
  121. if (!(strpos(" #;:0123456789-_.%", $char) === false)) {
  122. $cleaned .= $char;
  123. }
  124. }
  125. return $cleaned;
  126. }
  127. /**
  128. * @brief Converts [url] BBCodes in a format that looks fine on Mastodon. (callback function)
  129. * @param array $match Array with the matching values
  130. * @return string reformatted link including HTML codes
  131. */
  132. function bb_style_url($match) {
  133. $url = $match[1];
  134. if (isset($match[2]) && ($match[1] != $match[2])) {
  135. return $match[0];
  136. }
  137. $parts = parse_url($url);
  138. if (!isset($parts['scheme'])) {
  139. return $match[0];
  140. }
  141. return style_url_for_mastodon($url);
  142. }
  143. /**
  144. * @brief Converts [url] BBCodes in a format that looks fine on Mastodon and GNU Social.
  145. * @param string $url URL that is about to be reformatted
  146. * @return string reformatted link including HTML codes
  147. */
  148. function style_url_for_mastodon($url) {
  149. $styled_url = $url;
  150. $parts = parse_url($url);
  151. $scheme = $parts['scheme'].'://';
  152. $styled_url = str_replace($scheme, '', $styled_url);
  153. $html = '<a href="%s" class="attachment" rel="nofollow noopener" target="_blank">'.
  154. '<span class="invisible">%s</span>';
  155. if (strlen($styled_url) > 30) {
  156. $html .= '<span class="ellipsis">%s</span>'.
  157. '<span class="invisible">%s</span></a>';
  158. $ellipsis = substr($styled_url, 0, 30);
  159. $rest = substr($styled_url, 30);
  160. return sprintf($html, $url, $scheme, $ellipsis, $rest);
  161. } else {
  162. $html .= '%s</a>';
  163. return sprintf($html, $url, $scheme, $styled_url);
  164. }
  165. }
  166. function stripcode_br_cb($s) {
  167. return '[code]' . str_replace('<br />', '', $s[1]) . '[/code]';
  168. }
  169. function tryoembed($match) {
  170. $url = $match[1];
  171. // Always embed the SSL version
  172. $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
  173. array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
  174. $o = oembed_fetch_url($url);
  175. if (!is_object($o)) {
  176. return $match[0];
  177. }
  178. if (isset($match[2])) {
  179. $o->title = $match[2];
  180. }
  181. if ($o->type == "error") {
  182. return $match[0];
  183. }
  184. $html = oembed_format_object($o);
  185. return $html;
  186. }
  187. /*
  188. * [noparse][i]italic[/i][/noparse] turns into
  189. * [noparse][ i ]italic[ /i ][/noparse],
  190. * to hide them from parser.
  191. */
  192. function bb_spacefy($st) {
  193. $whole_match = $st[0];
  194. $captured = $st[1];
  195. $spacefied = preg_replace("/\[(.*?)\]/", "[ $1 ]", $captured);
  196. $new_str = str_replace($captured, $spacefied, $whole_match);
  197. return $new_str;
  198. }
  199. /*
  200. * The previously spacefied [noparse][ i ]italic[ /i ][/noparse],
  201. * now turns back and the [noparse] tags are trimed
  202. * returning [i]italic[/i]
  203. */
  204. function bb_unspacefy_and_trim($st) {
  205. $whole_match = $st[0];
  206. $captured = $st[1];
  207. $unspacefied = preg_replace("/\[ (.*?)\ ]/", "[$1]", $captured);
  208. return $unspacefied;
  209. }
  210. function bb_find_open_close($s, $open, $close, $occurence = 1) {
  211. if ($occurence < 1) {
  212. $occurence = 1;
  213. }
  214. $start_pos = -1;
  215. for ($i = 1; $i <= $occurence; $i++) {
  216. if ($start_pos !== false) {
  217. $start_pos = strpos($s, $open, $start_pos + 1);
  218. }
  219. }
  220. if ($start_pos === false) {
  221. return false;
  222. }
  223. $end_pos = strpos($s, $close, $start_pos);
  224. if ($end_pos === false) {
  225. return false;
  226. }
  227. $res = array( 'start' => $start_pos, 'end' => $end_pos );
  228. return $res;
  229. }
  230. function get_bb_tag_pos($s, $name, $occurence = 1) {
  231. if ($occurence < 1) {
  232. $occurence = 1;
  233. }
  234. $start_open = -1;
  235. for ($i = 1; $i <= $occurence; $i++) {
  236. if ($start_open !== false) {
  237. $start_open = strpos($s, '[' . $name, $start_open + 1); // allow [name= type tags
  238. }
  239. }
  240. if ($start_open === false) {
  241. return false;
  242. }
  243. $start_equal = strpos($s, '=', $start_open);
  244. $start_close = strpos($s, ']', $start_open);
  245. if ($start_close === false) {
  246. return false;
  247. }
  248. $start_close++;
  249. $end_open = strpos($s, '[/' . $name . ']', $start_close);
  250. if ($end_open === false) {
  251. return false;
  252. }
  253. $res = array(
  254. 'start' => array(
  255. 'open' => $start_open,
  256. 'close' => $start_close
  257. ),
  258. 'end' => array(
  259. 'open' => $end_open,
  260. 'close' => $end_open + strlen('[/' . $name . ']')
  261. ),
  262. );
  263. if ($start_equal !== false) {
  264. $res['start']['equal'] = $start_equal + 1;
  265. }
  266. return $res;
  267. }
  268. function bb_tag_preg_replace($pattern, $replace, $name, $s) {
  269. $string = $s;
  270. $occurence = 1;
  271. $pos = get_bb_tag_pos($string, $name, $occurence);
  272. while ($pos !== false && $occurence < 1000) {
  273. $start = substr($string, 0, $pos['start']['open']);
  274. $subject = substr($string, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']);
  275. $end = substr($string, $pos['end']['close']);
  276. if ($end === false) {
  277. $end = '';
  278. }
  279. $subject = preg_replace($pattern, $replace, $subject);
  280. $string = $start . $subject . $end;
  281. $occurence++;
  282. $pos = get_bb_tag_pos($string, $name, $occurence);
  283. }
  284. return $string;
  285. }
  286. if (! function_exists('bb_extract_images')) {
  287. function bb_extract_images($body) {
  288. $saved_image = array();
  289. $orig_body = $body;
  290. $new_body = '';
  291. $cnt = 0;
  292. $img_start = strpos($orig_body, '[img');
  293. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  294. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  295. while (($img_st_close !== false) && ($img_end !== false)) {
  296. $img_st_close++; // make it point to AFTER the closing bracket
  297. $img_end += $img_start;
  298. if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  299. // This is an embedded image
  300. $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close));
  301. $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]';
  302. $cnt++;
  303. } else {
  304. $new_body = $new_body . substr($orig_body, 0, $img_end + strlen('[/img]'));
  305. }
  306. $orig_body = substr($orig_body, $img_end + strlen('[/img]'));
  307. if ($orig_body === false) {
  308. // in case the body ends on a closing image tag
  309. $orig_body = '';
  310. }
  311. $img_start = strpos($orig_body, '[img');
  312. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  313. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  314. }
  315. $new_body = $new_body . $orig_body;
  316. return array('body' => $new_body, 'images' => $saved_image);
  317. }}
  318. if (! function_exists('bb_replace_images')) {
  319. function bb_replace_images($body, $images) {
  320. $newbody = $body;
  321. $cnt = 0;
  322. foreach ($images as $image) {
  323. // We're depending on the property of 'foreach' (specified on the PHP website) that
  324. // it loops over the array starting from the first element and going sequentially
  325. // to the last element
  326. $newbody = str_replace('[$#saved_image' . $cnt . '#$]', '<img src="' . proxy_url($image) .'" alt="' . t('Image/photo') . '" />', $newbody);
  327. $cnt++;
  328. }
  329. return $newbody;
  330. }}
  331. function bb_ShareAttributes($share, $simplehtml) {
  332. $attributes = $share[2];
  333. $author = "";
  334. preg_match("/author='(.*?)'/ism", $attributes, $matches);
  335. if ($matches[1] != "")
  336. $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
  337. preg_match('/author="(.*?)"/ism', $attributes, $matches);
  338. if ($matches[1] != "")
  339. $author = $matches[1];
  340. $profile = "";
  341. preg_match("/profile='(.*?)'/ism", $attributes, $matches);
  342. if ($matches[1] != "")
  343. $profile = $matches[1];
  344. preg_match('/profile="(.*?)"/ism', $attributes, $matches);
  345. if ($matches[1] != "")
  346. $profile = $matches[1];
  347. $avatar = "";
  348. preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
  349. if ($matches[1] != "")
  350. $avatar = $matches[1];
  351. preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
  352. if ($matches[1] != "")
  353. $avatar = $matches[1];
  354. $link = "";
  355. preg_match("/link='(.*?)'/ism", $attributes, $matches);
  356. if ($matches[1] != "")
  357. $link = $matches[1];
  358. preg_match('/link="(.*?)"/ism', $attributes, $matches);
  359. if ($matches[1] != "")
  360. $link = $matches[1];
  361. $posted = "";
  362. $itemcache = get_itemcachepath();
  363. preg_match("/posted='(.*?)'/ism", $attributes, $matches);
  364. if ($matches[1] != "")
  365. $posted = $matches[1];
  366. preg_match('/posted="(.*?)"/ism', $attributes, $matches);
  367. if ($matches[1] != "")
  368. $posted = $matches[1];
  369. // relative dates only make sense when they aren't cached
  370. if ($itemcache == "")
  371. $reldate = (($posted) ? " " . relative_date($posted) : '');
  372. // We only call this so that a previously unknown contact can be added.
  373. // This is important for the function "get_contact_details_by_url".
  374. // This function then can fetch an entry from the contact table.
  375. get_contact($profile, 0);
  376. $data = get_contact_details_by_url($profile);
  377. if (isset($data["name"]) && ($data["name"] != "") && isset($data["addr"]) && ($data["addr"] != ""))
  378. $userid_compact = $data["name"]." (".$data["addr"].")";
  379. else
  380. $userid_compact = GetProfileUsername($profile,$author, true);
  381. if (isset($data["addr"]) && ($data["addr"] != ""))
  382. $userid = $data["addr"];
  383. else
  384. $userid = GetProfileUsername($profile,$author, false);
  385. if (isset($data["name"]) && ($data["name"] != ""))
  386. $author = $data["name"];
  387. if (isset($data["micro"]) && ($data["micro"] != ""))
  388. $avatar = $data["micro"];
  389. $preshare = trim($share[1]);
  390. if ($preshare != "")
  391. $preshare .= "<br /><br />";
  392. switch ($simplehtml) {
  393. case 1:
  394. $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' <a href="'.$profile.'">'.$userid."</a>: <br />»".$share[3]."«";
  395. break;
  396. case 2:
  397. $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
  398. break;
  399. case 3: // Diaspora
  400. $headline .= '<b>'.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').$userid.':</b><br />';
  401. $text = trim($share[1]);
  402. if ($text != "")
  403. $text .= "<hr />";
  404. if (substr(normalise_link($link), 0, 19) != "http://twitter.com/") {
  405. $text .= $headline.'<blockquote>'.trim($share[3])."</blockquote><br />";
  406. if ($link != "")
  407. $text .= '<br /><a href="'.$link.'">[l]</a>';
  408. } else
  409. $text .= '<br /><a href="'.$link.'">'.$link.'</a>';
  410. break;
  411. case 4:
  412. $headline = '<div class="shared_header">';
  413. $headline .= '<span><b>'.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
  414. $headline .= sprintf(t('<a href="%1$s" target="_blank">%2$s</a> %3$s'), $link, $userid, $posted);
  415. $headline .= ":</b></span></div>";
  416. $text = trim($share[1]);
  417. if ($text != "")
  418. $text .= "<hr />";
  419. $text .= $headline.'<blockquote class="shared_content">'.trim($share[3])."</blockquote><br />";
  420. break;
  421. case 5:
  422. $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
  423. break;
  424. case 6: // app.net
  425. $text = $preshare."&gt;&gt; @".$userid_compact.": <br />".$share[3];
  426. break;
  427. case 7: // statusnet/GNU Social
  428. $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')." @".$userid_compact.": ".$share[3];
  429. break;
  430. case 8: // twitter
  431. $text = $preshare."RT @".$userid_compact.": ".$share[3];
  432. break;
  433. case 9: // Google+/Facebook
  434. $text = $preshare.html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8').' '.$userid_compact.": <br />".$share[3];
  435. if ($link != "")
  436. $text .= "<br /><br />".$link;
  437. break;
  438. default:
  439. $text = trim($share[1])."\n";
  440. $avatar = proxy_url($avatar, false, PROXY_SIZE_THUMB);
  441. $tpl = get_markup_template('shared_content.tpl');
  442. $text .= replace_macros($tpl,
  443. array(
  444. '$profile' => $profile,
  445. '$avatar' => $avatar,
  446. '$author' => $author,
  447. '$link' => $link,
  448. '$posted' => $posted,
  449. '$reldate' => $reldate,
  450. '$content' => trim($share[3])
  451. )
  452. );
  453. break;
  454. }
  455. return $text;
  456. }
  457. function GetProfileUsername($profile, $username, $compact = false, $getnetwork = false) {
  458. $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1@twitter.com", $profile);
  459. if ($twitter != $profile) {
  460. if ($getnetwork) {
  461. return NETWORK_TWITTER;
  462. } elseif ($compact) {
  463. return $twitter;
  464. } else {
  465. return ($username . " (" . $twitter . ")");
  466. }
  467. }
  468. $appnet = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1@alpha.app.net", $profile);
  469. if ($appnet != $profile) {
  470. if ($getnetwork) {
  471. return NETWORK_APPNET;
  472. } elseif ($compact) {
  473. return $appnet;
  474. } else {
  475. return ($username . " (" . $appnet . ")");
  476. }
  477. }
  478. $gplus = preg_replace("=https?://plus.google.com/(.*)=ism", "$1@plus.google.com", $profile);
  479. if ($gplus != $profile) {
  480. if ($getnetwork) {
  481. return NETWORK_GPLUS;
  482. } elseif ($compact) {
  483. return ($gplususername . " (" . $username . ")");
  484. } else {
  485. return ($username . " (" . $gplus . ")");
  486. }
  487. }
  488. $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2@$1", $profile);
  489. if ($friendica != $profile) {
  490. if ($getnetwork) {
  491. return NETWORK_DFRN;
  492. } elseif ($compact) {
  493. return $friendica;
  494. } else {
  495. return ($username . " (" . $friendica . ")");
  496. }
  497. }
  498. $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
  499. if ($diaspora != $profile) {
  500. if ($getnetwork) {
  501. return NETWORK_DIASPORA;
  502. } elseif ($compact) {
  503. return $diaspora;
  504. } else {
  505. return ($username . " (" . $diaspora . ")");
  506. }
  507. }
  508. $red = preg_replace("=https?://(.*)/channel/(.*)=ism", "$2@$1", $profile);
  509. if ($red != $profile) {
  510. if ($getnetwork) {
  511. // red is identified as Diaspora - friendica can't connect directly to it
  512. return NETWORK_DIASPORA;
  513. } elseif ($compact) {
  514. return $red;
  515. } else {
  516. return ($username . " (" . $red . ")");
  517. }
  518. }
  519. $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
  520. if ($StatusnetHost != $profile) {
  521. $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
  522. if ($StatusnetUser != $profile) {
  523. /// @TODO Some hosts run on https, not just http and sometimes http is disabled, let's support both here
  524. $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
  525. $user = json_decode($UserData);
  526. if ($user) {
  527. if ($getnetwork) {
  528. return NETWORK_STATUSNET;
  529. } elseif ($compact) {
  530. return ($user->screen_name . "@" . $StatusnetHost);
  531. } else {
  532. return ($username . " (" . $user->screen_name . "@" . $StatusnetHost . ")");
  533. }
  534. }
  535. }
  536. }
  537. // pumpio (http://host.name/user)
  538. $rest = preg_replace("=https?://([\.\w]+)/([\.\w]+)(.*)=ism", "$3", $profile);
  539. if ($rest == "") {
  540. $pumpio = preg_replace("=https?://([\.\w]+)/([\.\w]+)(.*)=ism", "$2@$1", $profile);
  541. if ($pumpio != $profile) {
  542. if ($getnetwork) {
  543. return NETWORK_PUMPIO;
  544. } elseif ($compact) {
  545. return $pumpio;
  546. } else {
  547. return ($username . " (" . $pumpio . ")");
  548. }
  549. }
  550. }
  551. return $username;
  552. }
  553. function bb_DiasporaLinks($match) {
  554. return "[url=".App::get_baseurl()."/display/".$match[1]."]".$match[2]."[/url]";
  555. }
  556. function bb_RemovePictureLinks($match) {
  557. $text = Cache::get($match[1]);
  558. if (is_null($text)) {
  559. $a = get_app();
  560. $stamp1 = microtime(true);
  561. $ch = @curl_init($match[1]);
  562. @curl_setopt($ch, CURLOPT_NOBODY, true);
  563. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  564. @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  565. @curl_exec($ch);
  566. $curl_info = @curl_getinfo($ch);
  567. $a->save_timestamp($stamp1, "network");
  568. if (substr($curl_info["content_type"], 0, 6) == "image/")
  569. $text = "[url=".$match[1]."]".$match[1]."[/url]";
  570. else {
  571. $text = "[url=".$match[2]."]".$match[2]."[/url]";
  572. // if its not a picture then look if its a page that contains a picture link
  573. require_once("include/network.php");
  574. $body = fetch_url($match[1]);
  575. $doc = new DOMDocument();
  576. @$doc->loadHTML($body);
  577. $xpath = new DomXPath($doc);
  578. $list = $xpath->query("//meta[@name]");
  579. foreach ($list as $node) {
  580. $attr = array();
  581. if ($node->attributes->length)
  582. foreach ($node->attributes as $attribute)
  583. $attr[$attribute->name] = $attribute->value;
  584. if (strtolower($attr["name"]) == "twitter:image")
  585. $text = "[url=".$attr["content"]."]".$attr["content"]."[/url]";
  586. }
  587. }
  588. Cache::set($match[1],$text);
  589. }
  590. return $text;
  591. }
  592. function bb_expand_links($match) {
  593. if (($match[3] == "") || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
  594. return ($match[1] . "[url]" . $match[2] . "[/url]");
  595. } else {
  596. return ($match[1] . $match[3] . " [url]" . $match[2] . "[/url]");
  597. }
  598. }
  599. function bb_CleanPictureLinksSub($match) {
  600. $text = Cache::get($match[1]);
  601. if (is_null($text)) {
  602. $a = get_app();
  603. $stamp1 = microtime(true);
  604. $ch = @curl_init($match[1]);
  605. @curl_setopt($ch, CURLOPT_NOBODY, true);
  606. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  607. @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  608. @curl_exec($ch);
  609. $curl_info = @curl_getinfo($ch);
  610. $a->save_timestamp($stamp1, "network");
  611. // if its a link to a picture then embed this picture
  612. if (substr($curl_info["content_type"], 0, 6) == "image/")
  613. $text = "[img]".$match[1]."[/img]";
  614. else {
  615. $text = "[img]".$match[2]."[/img]";
  616. // if its not a picture then look if its a page that contains a picture link
  617. require_once("include/network.php");
  618. $body = fetch_url($match[1]);
  619. $doc = new DOMDocument();
  620. @$doc->loadHTML($body);
  621. $xpath = new DomXPath($doc);
  622. $list = $xpath->query("//meta[@name]");
  623. foreach ($list as $node) {
  624. $attr = array();
  625. if ($node->attributes->length)
  626. foreach ($node->attributes as $attribute)
  627. $attr[$attribute->name] = $attribute->value;
  628. if (strtolower($attr["name"]) == "twitter:image")
  629. $text = "[img]".$attr["content"]."[/img]";
  630. }
  631. }
  632. Cache::set($match[1],$text);
  633. }
  634. return $text;
  635. }
  636. function bb_CleanPictureLinks($text) {
  637. $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'bb_CleanPictureLinksSub', $text);
  638. return $text;
  639. }
  640. function bb_highlight($match) {
  641. if (in_array(strtolower($match[1]), ['php', 'css', 'mysql', 'sql', 'abap', 'diff', 'html', 'perl', 'ruby',
  642. 'vbscript', 'avrc', 'dtd', 'java', 'xml', 'cpp', 'python', 'javascript', 'js', 'sh'])) {
  643. return text_highlight($match[2], strtolower($match[1]));
  644. }
  645. return $match[0];
  646. }
  647. /**
  648. * @brief Converts a BBCode message to HTML message
  649. *
  650. * BBcode 2 HTML was written by WAY2WEB.net
  651. * extended to work with Mistpark/Friendica - Mike Macgirvin
  652. *
  653. * Simple HTML values meaning:
  654. * - 0: Friendica display
  655. * - 1: Unused
  656. * - 2: Used for Facebook, Google+, Windows Phone push, Friendica API
  657. * - 3: Used before converting to Markdown in bb2diaspora.php
  658. * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr
  659. * - 5: Unused
  660. * - 6: Used for Appnet
  661. * - 7: Used for dfrn, OStatus
  662. * - 8: Used for WP backlink text setting
  663. *
  664. * @staticvar array $allowed_src_protocols
  665. * @param string $Text
  666. * @param bool $preserve_nl
  667. * @param bool $tryoembed
  668. * @param int $simplehtml
  669. * @param bool $forplaintext
  670. * @return string
  671. */
  672. function bbcode($Text, $preserve_nl = false, $tryoembed = true, $simplehtml = false, $forplaintext = false) {
  673. $a = get_app();
  674. // Hide all [noparse] contained bbtags by spacefying them
  675. // POSSIBLE BUG --> Will the 'preg' functions crash if there's an embedded image?
  676. $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_spacefy', $Text);
  677. $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_spacefy', $Text);
  678. $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_spacefy', $Text);
  679. // Remove the abstract element. It is a non visible element.
  680. $Text = remove_abstract($Text);
  681. // Move all spaces out of the tags
  682. $Text = preg_replace("/\[(\w*)\](\s*)/ism", '$2[$1]', $Text);
  683. $Text = preg_replace("/(\s*)\[\/(\w*)\]/ism", '[/$2]$1', $Text);
  684. // Extract the private images which use data urls since preg has issues with
  685. // large data sizes. Stash them away while we do bbcode conversion, and then put them back
  686. // in after we've done all the regex matching. We cannot use any preg functions to do this.
  687. $extracted = bb_extract_images($Text);
  688. $Text = $extracted['body'];
  689. $saved_image = $extracted['images'];
  690. // If we find any event code, turn it into an event.
  691. // After we're finished processing the bbcode we'll
  692. // replace all of the event code with a reformatted version.
  693. $ev = bbtoevent($Text);
  694. // Replace any html brackets with HTML Entities to prevent executing HTML or script
  695. // Don't use strip_tags here because it breaks [url] search by replacing & with amp
  696. $Text = str_replace("<", "&lt;", $Text);
  697. $Text = str_replace(">", "&gt;", $Text);
  698. // remove some newlines before the general conversion
  699. $Text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "[share$1]$2[/share]", $Text);
  700. $Text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "[quote$1]$2[/quote]", $Text);
  701. $Text = preg_replace("/\n\[code\]/ism", "[code]", $Text);
  702. $Text = preg_replace("/\[\/code\]\n/ism", "[/code]", $Text);
  703. // when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
  704. if (!$tryoembed) {
  705. $Text = preg_replace("/\[share(.*?)avatar\s?=\s?'.*?'\s?(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1$2]$3[/share]", $Text);
  706. }
  707. // Check for [code] text here, before the linefeeds are messed with.
  708. // The highlighter will unescape and re-escape the content.
  709. if (strpos($Text, '[code=') !== false) {
  710. $Text = preg_replace_callback("/\[code=(.*?)\](.*?)\[\/code\]/ism", 'bb_highlight', $Text);
  711. }
  712. // Convert new line chars to html <br /> tags
  713. // nlbr seems to be hopelessly messed up
  714. // $Text = nl2br($Text);
  715. // We'll emulate it.
  716. $Text = trim($Text);
  717. $Text = str_replace("\r\n", "\n", $Text);
  718. // removing multiplicated newlines
  719. if (get_config("system", "remove_multiplicated_lines")) {
  720. $search = array("\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[ul]", "[/ul]\n", "\n\n[share ", "[/attachment]\n",
  721. "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n");
  722. $replace = array("\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[ul]", "[/ul]", "\n[share ", "[/attachment]",
  723. "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]");
  724. do {
  725. $oldtext = $Text;
  726. $Text = str_replace($search, $replace, $Text);
  727. } while ($oldtext != $Text);
  728. }
  729. // Handle attached links or videos
  730. $Text = bb_attachment($Text, $simplehtml, $tryoembed);
  731. $Text = str_replace(array("\r","\n"), array('<br />', '<br />'), $Text);
  732. if ($preserve_nl) {
  733. $Text = str_replace(array("\n", "\r"), array('', ''), $Text);
  734. }
  735. // Set up the parameters for a URL search string
  736. $URLSearchString = "^\[\]";
  737. // Set up the parameters for a MAIL search string
  738. $MAILSearchString = $URLSearchString;
  739. // Remove all hashtag addresses
  740. if ((!$tryoembed || $simplehtml) && !in_array($simplehtml, array(3, 7))) {
  741. $Text = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
  742. } elseif ($simplehtml == 3) {
  743. $Text = preg_replace("/([@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  744. '$1<a href="$2">$3</a>',
  745. $Text);
  746. } elseif ($simplehtml == 7) {
  747. $Text = preg_replace("/([@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  748. '$1<span class="vcard"><a href="$2" class="url" title="$3"><span class="fn nickname mention">$3</span></a></span>',
  749. $Text);
  750. } elseif (!$simplehtml) {
  751. $Text = preg_replace("/([@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  752. '$1<a href="$2" class="userinfo mention" title="$3">$3</a>',
  753. $Text);
  754. }
  755. // Bookmarks in red - will be converted to bookmarks in friendica
  756. $Text = preg_replace("/#\^\[url\]([$URLSearchString]*)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $Text);
  757. $Text = preg_replace("/#\^\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $Text);
  758. $Text = preg_replace("/#\[url\=[$URLSearchString]*\]\^\[\/url\]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/i",
  759. "[bookmark=$1]$2[/bookmark]", $Text);
  760. if (in_array($simplehtml, array(2, 6, 7, 8, 9))) {
  761. $Text = preg_replace_callback("/([^#@])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", "bb_expand_links", $Text);
  762. //$Text = preg_replace("/[^#@]\[url\=([^\]]*)\](.*?)\[\/url\]/ism", ' $2 [url]$1[/url]', $Text);
  763. $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", ' $2 [url]$1[/url]',$Text);
  764. }
  765. if ($simplehtml == 5) {
  766. $Text = preg_replace("/[^#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url]$1[/url]', $Text);
  767. }
  768. // Perform URL Search
  769. if ($tryoembed) {
  770. $Text = preg_replace_callback("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", 'tryoembed', $Text);
  771. }
  772. if ($simplehtml == 5) {
  773. $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url]$1[/url]', $Text);
  774. } else {
  775. $Text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $Text);
  776. }
  777. // Handle Diaspora posts
  778. $Text = preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi", 'bb_DiasporaLinks', $Text);
  779. // if the HTML is used to generate plain text, then don't do this search, but replace all URL of that kind to text
  780. // if ($simplehtml != 7) {
  781. if (!$forplaintext) {
  782. if ($simplehtml != 7) {
  783. $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1<a href="$2" target="_blank">$2</a>', $Text);
  784. } else {
  785. $Text = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url]$2[/url]', $Text);
  786. $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'bb_style_url', $Text);
  787. $Text = preg_replace_callback("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", 'bb_style_url', $Text);
  788. }
  789. } else {
  790. $Text = preg_replace("(\[url\]([$URLSearchString]*)\[\/url\])ism", " $1 ", $Text);
  791. $Text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'bb_RemovePictureLinks', $Text);
  792. }
  793. // }
  794. if ($tryoembed) {
  795. $Text = preg_replace_callback("/\[url\]([$URLSearchString]*)\[\/url\]/ism", 'tryoembed', $Text);
  796. }
  797. $Text = preg_replace("/([#])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  798. '$1<a href="$2" class="tag" title="$3">$3</a>', $Text);
  799. $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$1</a>', $Text);
  800. $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
  801. //$Text = preg_replace("/\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[\/url\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
  802. // Red compatibility, though the link can't be authenticated on Friendica
  803. $Text = preg_replace("/\[zrl\=([$URLSearchString]*)\](.*?)\[\/zrl\]/ism", '<a href="$1" target="_blank">$2</a>', $Text);
  804. // we may need to restrict this further if it picks up too many strays
  805. // link acct:user@host to a webfinger profile redirector
  806. $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="' . App::get_baseurl() . '/acctlink?addr=$1@$2" target="extlink">acct:$1@$2</a>', $Text);
  807. // Perform MAIL Search
  808. $Text = preg_replace("/\[mail\]([$MAILSearchString]*)\[\/mail\]/", '<a href="mailto:$1">$1</a>', $Text);
  809. $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.*?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);
  810. // leave open the posibility of [map=something]
  811. // this is replaced in prepare_body() which has knowledge of the item location
  812. if (strpos($Text, '[/map]') !== false) {
  813. $Text = preg_replace_callback("/\[map\](.*?)\[\/map\]/ism", 'bb_map_location', $Text);
  814. }
  815. if (strpos($Text, '[map=') !== false) {
  816. $Text = preg_replace_callback("/\[map=(.*?)\]/ism", 'bb_map_coords', $Text);
  817. }
  818. if (strpos($Text, '[map]') !== false) {
  819. $Text = preg_replace("/\[map\]/", '<div class="map"></div>', $Text);
  820. }
  821. // Check for headers
  822. $Text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '<h1>$1</h1>', $Text);
  823. $Text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '<h2>$1</h2>', $Text);
  824. $Text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '<h3>$1</h3>', $Text);
  825. $Text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '<h4>$1</h4>', $Text);
  826. $Text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '<h5>$1</h5>', $Text);
  827. $Text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '<h6>$1</h6>', $Text);
  828. // Check for paragraph
  829. $Text = preg_replace("(\[p\](.*?)\[\/p\])ism", '<p>$1</p>', $Text);
  830. // Check for bold text
  831. $Text = preg_replace("(\[b\](.*?)\[\/b\])ism", '<strong>$1</strong>', $Text);
  832. // Check for Italics text
  833. $Text = preg_replace("(\[i\](.*?)\[\/i\])ism", '<em>$1</em>', $Text);
  834. // Check for Underline text
  835. $Text = preg_replace("(\[u\](.*?)\[\/u\])ism", '<u>$1</u>', $Text);
  836. // Check for strike-through text
  837. $Text = preg_replace("(\[s\](.*?)\[\/s\])ism", '<strike>$1</strike>', $Text);
  838. // Check for over-line text
  839. $Text = preg_replace("(\[o\](.*?)\[\/o\])ism", '<span class="overline">$1</span>', $Text);
  840. // Check for colored text
  841. $Text = preg_replace("(\[color=(.*?)\](.*?)\[\/color\])ism", "<span style=\"color: $1;\">$2</span>", $Text);
  842. // Check for sized text
  843. // [size=50] --> font-size: 50px (with the unit).
  844. $Text = preg_replace("(\[size=(\d*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1px; line-height: initial;\">$2</span>", $Text);
  845. $Text = preg_replace("(\[size=(.*?)\](.*?)\[\/size\])ism", "<span style=\"font-size: $1; line-height: initial;\">$2</span>", $Text);
  846. // Check for centered text
  847. $Text = preg_replace("(\[center\](.*?)\[\/center\])ism", "<div style=\"text-align:center;\">$1</div>", $Text);
  848. // Check for list text
  849. $Text = str_replace("[*]", "<li>", $Text);
  850. // Check for style sheet commands
  851. $Text = preg_replace_callback("(\[style=(.*?)\](.*?)\[\/style\])ism", "bb_cleanstyle", $Text);
  852. // Check for CSS classes
  853. $Text = preg_replace_callback("(\[class=(.*?)\](.*?)\[\/class\])ism", "bb_cleanclass", $Text);
  854. // handle nested lists
  855. $endlessloop = 0;
  856. while ((((strpos($Text, "[/list]") !== false) && (strpos($Text, "[list") !== false)) ||
  857. ((strpos($Text, "[/ol]") !== false) && (strpos($Text, "[ol]") !== false)) ||
  858. ((strpos($Text, "[/ul]") !== false) && (strpos($Text, "[ul]") !== false)) ||
  859. ((strpos($Text, "[/li]") !== false) && (strpos($Text, "[li]") !== false))) && (++$endlessloop < 20)) {
  860. $Text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $Text);
  861. $Text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>', $Text);
  862. $Text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $Text);
  863. $Text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>', $Text);
  864. $Text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>', $Text);
  865. $Text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>', $Text);
  866. $Text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>', $Text);
  867. $Text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $Text);
  868. $Text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $Text);
  869. $Text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $Text);
  870. }
  871. $Text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $Text);
  872. $Text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $Text);
  873. $Text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $Text);
  874. $Text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>', $Text);
  875. $Text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>', $Text);
  876. $Text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>', $Text);
  877. $Text = str_replace('[hr]', '<hr />', $Text);
  878. // This is actually executed in prepare_body()
  879. $Text = str_replace('[nosmile]', '', $Text);
  880. // Check for font change text
  881. $Text = preg_replace("/\[font=(.*?)\](.*?)\[\/font\]/sm", "<span style=\"font-family: $1;\">$2</span>", $Text);
  882. // Declare the format for [code] layout
  883. // $Text = preg_replace_callback("/\[code\](.*?)\[\/code\]/ism", 'stripcode_br_cb', $Text);
  884. $CodeLayout = '<code>$1</code>';
  885. // Check for [code] text
  886. $Text = preg_replace("/\[code\](.*?)\[\/code\]/ism", "$CodeLayout", $Text);
  887. // Declare the format for [spoiler] layout
  888. $SpoilerLayout = '<blockquote class="spoiler">$1</blockquote>';
  889. // Check for [spoiler] text
  890. // handle nested quotes
  891. $endlessloop = 0;
  892. while ((strpos($Text, "[/spoiler]") !== false) && (strpos($Text, "[spoiler]") !== false) && (++$endlessloop < 20)) {
  893. $Text = preg_replace("/\[spoiler\](.*?)\[\/spoiler\]/ism", "$SpoilerLayout", $Text);
  894. }
  895. // Check for [spoiler=Author] text
  896. $t_wrote = t('$1 wrote:');
  897. // handle nested quotes
  898. $endlessloop = 0;
  899. while ((strpos($Text, "[/spoiler]")!== false) && (strpos($Text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
  900. $Text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
  901. "<br /><strong class=".'"spoiler"'.">" . $t_wrote . "</strong><blockquote class=".'"spoiler"'.">$2</blockquote>",
  902. $Text);
  903. }
  904. // Declare the format for [quote] layout
  905. $QuoteLayout = '<blockquote>$1</blockquote>';
  906. // Check for [quote] text
  907. // handle nested quotes
  908. $endlessloop = 0;
  909. while ((strpos($Text, "[/quote]") !== false) && (strpos($Text, "[quote]") !== false) && (++$endlessloop < 20)) {
  910. $Text = preg_replace("/\[quote\](.*?)\[\/quote\]/ism", "$QuoteLayout", $Text);
  911. }
  912. // Check for [quote=Author] text
  913. $t_wrote = t('$1 wrote:');
  914. // handle nested quotes
  915. $endlessloop = 0;
  916. while ((strpos($Text, "[/quote]")!== false) && (strpos($Text, "[quote=") !== false) && (++$endlessloop < 20)) {
  917. $Text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
  918. "<br /><strong class=".'"author"'.">" . $t_wrote . "</strong><blockquote>$2</blockquote>",
  919. $Text);
  920. }
  921. // [img=widthxheight]image source[/img]
  922. $Text = preg_replace_callback("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", 'bb_PictureCacheExt', $Text);
  923. $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $Text);
  924. $Text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $Text);
  925. // Images
  926. // [img]pathtoimage[/img]
  927. $Text = preg_replace_callback("/\[img\](.*?)\[\/img\]/ism", 'bb_PictureCache', $Text);
  928. $Text = preg_replace("/\[img\](.*?)\[\/img\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
  929. $Text = preg_replace("/\[zmg\](.*?)\[\/zmg\]/ism", '<img src="$1" alt="' . t('Image/photo') . '" />', $Text);
  930. // Shared content
  931. $Text = preg_replace_callback("/(.*?)\[share(.*?)\](.*?)\[\/share\]/ism",
  932. function ($match) use ($simplehtml) {
  933. return bb_ShareAttributes($match, $simplehtml);
  934. }, $Text);
  935. $Text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism", '<br/><img src="' .App::get_baseurl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . t('Encrypted content') . '" /><br />', $Text);
  936. $Text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism", '<br/><img src="' .App::get_baseurl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . '$1' . ' ' . t('Encrypted content') . '" /><br />', $Text);
  937. //$Text = preg_replace("/\[crypt=(.*?)\](.*?)\[\/crypt\]/ism", '<br/><img src="' .App::get_baseurl() . '/images/lock_icon.gif" alt="' . t('Encrypted content') . '" title="' . '$1' . ' ' . t('Encrypted content') . '" /><br />', $Text);
  938. // Try to Oembed
  939. if ($tryoembed) {
  940. $Text = preg_replace("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4))\[\/video\]/ism", '<video src="$1" controls="controls" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></video>', $Text);
  941. $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);
  942. $Text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", 'tryoembed', $Text);
  943. $Text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", 'tryoembed', $Text);
  944. } else {
  945. $Text = preg_replace("/\[video\](.*?)\[\/video\]/",
  946. '<a href="$1" target="_blank">$1</a>', $Text);
  947. $Text = preg_replace("/\[audio\](.*?)\[\/audio\]/",
  948. '<a href="$1" target="_blank">$1</a>', $Text);
  949. }
  950. // html5 video and audio
  951. if ($tryoembed) {
  952. $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<iframe src="$1" width="' . $a->videowidth . '" height="' . $a->videoheight . '"><a href="$1">$1</a></iframe>', $Text);
  953. } else {
  954. $Text = preg_replace("/\[iframe\](.*?)\[\/iframe\]/ism", '<a href="$1">$1</a>', $Text);
  955. }
  956. // Youtube extensions
  957. if ($tryoembed) {
  958. $Text = preg_replace_callback("/\[youtube\](https?:\/\/www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
  959. $Text = preg_replace_callback("/\[youtube\](www.youtube.com\/watch\?v\=.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
  960. $Text = preg_replace_callback("/\[youtube\](https?:\/\/youtu.be\/.*?)\[\/youtube\]/ism", 'tryoembed', $Text);
  961. }
  962. $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
  963. $Text = preg_replace("/\[youtube\]https?:\/\/www.youtube.com\/embed\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
  964. $Text = preg_replace("/\[youtube\]https?:\/\/youtu.be\/(.*?)\[\/youtube\]/ism", '[youtube]$1[/youtube]', $Text);
  965. if ($tryoembed) {
  966. $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);
  967. } else {
  968. $Text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
  969. '<a href="https://www.youtube.com/watch?v=$1" target="_blank">https://www.youtube.com/watch?v=$1</a>', $Text);
  970. }
  971. if ($tryoembed) {
  972. $Text = preg_replace_callback("/\[vimeo\](https?:\/\/player.vimeo.com\/video\/[0-9]+).*?\[\/vimeo\]/ism", 'tryoembed', $Text);
  973. $Text = preg_replace_callback("/\[vimeo\](https?:\/\/vimeo.com\/[0-9]+).*?\[\/vimeo\]/ism", 'tryoembed', $Text);
  974. }
  975. $Text = preg_replace("/\[vimeo\]https?:\/\/player.vimeo.com\/video\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text);
  976. $Text = preg_replace("/\[vimeo\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/vimeo\]/ism", '[vimeo]$1[/vimeo]', $Text);
  977. if ($tryoembed) {
  978. $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);
  979. } else {
  980. $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
  981. '<a href="https://vimeo.com/$1" target="_blank">https://vimeo.com/$1</a>', $Text);
  982. }
  983. // $Text = preg_replace("/\[youtube\](.*?)\[\/youtube\]/", '<object width="425" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/$1" ><param name="movie" value="http://www.youtube.com/v/$1"></param><!--[if IE]><embed src="http://www.youtube.com/v/$1" type="application/x-shockwave-flash" width="425" height="350" /><![endif]--></object>', $Text);
  984. // oembed tag
  985. $Text = oembed_bbcode2html($Text);
  986. // Avoid triple linefeeds through oembed
  987. $Text = str_replace("<br style='clear:left'></span><br /><br />", "<br style='clear:left'></span><br />", $Text);
  988. // If we found an event earlier, strip out all the event code and replace with a reformatted version.
  989. // Replace the event-start section with the entire formatted event. The other bbcode is stripped.
  990. // Summary (e.g. title) is required, earlier revisions only required description (in addition to
  991. // start which is always required). Allow desc with a missing summary for compatibility.
  992. if ((x($ev, 'desc') || x($ev, 'summary')) && x($ev, 'start')) {
  993. $sub = format_event_html($ev, $simplehtml);
  994. $Text = preg_replace("/\[event\-summary\](.*?)\[\/event\-summary\]/ism", '', $Text);
  995. $Text = preg_replace("/\[event\-description\](.*?)\[\/event\-description\]/ism", '', $Text);
  996. $Text = preg_replace("/\[event\-start\](.*?)\[\/event\-start\]/ism", $sub, $Text);
  997. $Text = preg_replace("/\[event\-finish\](.*?)\[\/event\-finish\]/ism", '', $Text);
  998. $Text = preg_replace("/\[event\-location\](.*?)\[\/event\-location\]/ism", '', $Text);
  999. $Text = preg_replace("/\[event\-adjust\](.*?)\[\/event\-adjust\]/ism", '', $Text);
  1000. $Text = preg_replace("/\[event\-id\](.*?)\[\/event\-id\]/ism", '', $Text);
  1001. }
  1002. // Replace inline code blocks
  1003. $Text = preg_replace_callback("|(?!<br[^>]*>)<code>([^<]*)</code>(?!<br[^>]*>)|ism",
  1004. function ($match) use ($simplehtml) {
  1005. $return = '<key>' . $match[1] . '</key>';
  1006. // Use <code> for Diaspora inline code blocks
  1007. if ($simplehtml === 3) {
  1008. $return = '<code>' . $match[1] . '</code>';
  1009. }
  1010. return $return;
  1011. }
  1012. , $Text);
  1013. // Unhide all [noparse] contained bbtags unspacefying them
  1014. // and triming the [noparse] tag.
  1015. $Text = preg_replace_callback("/\[noparse\](.*?)\[\/noparse\]/ism", 'bb_unspacefy_and_trim', $Text);
  1016. $Text = preg_replace_callback("/\[nobb\](.*?)\[\/nobb\]/ism", 'bb_unspacefy_and_trim', $Text);
  1017. $Text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", 'bb_unspacefy_and_trim', $Text);
  1018. $Text = preg_replace('/\[\&amp\;([#a-z0-9]+)\;\]/', '&$1;', $Text);
  1019. $Text = preg_replace('/\&\#039\;/', '\'', $Text);
  1020. $Text = preg_replace('/\&quot\;/', '"', $Text);
  1021. // fix any escaped ampersands that may have been converted into links
  1022. $Text = preg_replace('/\<([^>]*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism', '<$1$2=$3&$4>', $Text);
  1023. // sanitizes src attributes (http and redir URLs for displaying in a web page, cid used for inline images in emails)
  1024. static $allowed_src_protocols = array('http', 'redir', 'cid');
  1025. $Text = preg_replace('#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
  1026. '<$1$2=""$4 class="invalid-src" title="' . t('Invalid source protocol') . '">', $Text);
  1027. // sanitize href attributes (only whitelisted protocols URLs)
  1028. // default value for backward compatibility
  1029. $allowed_link_protocols = Config::get('system', 'allowed_link_protocols', array('ftp', 'mailto', 'gopher', 'cid'));
  1030. // Always allowed protocol even if config isn't set or not including it
  1031. $allowed_link_protocols[] = 'http';
  1032. $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
  1033. $Text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 class="invalid-href" title="' . t('Invalid link protocol') . '">', $Text);
  1034. if ($saved_image) {
  1035. $Text = bb_replace_images($Text, $saved_image);
  1036. }
  1037. // Clean up the HTML by loading and saving the HTML with the DOM.
  1038. // Bad structured html can break a whole page.
  1039. // For performance reasons do it only with ativated item cache or at export.
  1040. if (!$tryoembed || (get_itemcachepath() != "")) {
  1041. $doc = new DOMDocument();
  1042. $doc->preserveWhiteSpace = false;
  1043. $Text = mb_convert_encoding($Text, 'HTML-ENTITIES', "UTF-8");
  1044. $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
  1045. $encoding = '<?xml encoding="UTF-8">';
  1046. @$doc->loadHTML($encoding.$doctype."<html><body>".$Text."</body></html>");
  1047. $doc->encoding = 'UTF-8';
  1048. $Text = $doc->saveHTML();
  1049. $Text = str_replace(array("<html><body>", "</body></html>", $doctype, $encoding), array("", "", "", ""), $Text);
  1050. $Text = str_replace('<br></li>', '</li>', $Text);
  1051. //$Text = mb_convert_encoding($Text, "UTF-8", 'HTML-ENTITIES');
  1052. }
  1053. // Clean up some useless linebreaks in lists
  1054. //$Text = str_replace('<br /><ul', '<ul ', $Text);
  1055. //$Text = str_replace('</ul><br />', '</ul>', $Text);
  1056. //$Text = str_replace('</li><br />', '</li>', $Text);
  1057. //$Text = str_replace('<br /><li>', '<li>', $Text);
  1058. //$Text = str_replace('<br /><ul', '<ul ', $Text);
  1059. call_hooks('bbcode', $Text);
  1060. return trim($Text);
  1061. }
  1062. /**
  1063. * @brief Removes the "abstract" element from the text
  1064. *
  1065. * @param string $text The text with BBCode
  1066. * @return string The same text - but without "abstract" element
  1067. */
  1068. function remove_abstract($text) {
  1069. $text = preg_replace("/[\s|\n]*\[abstract\].*?\[\/abstract\][\s|\n]*/ism", '', $text);
  1070. $text = preg_replace("/[\s|\n]*\[abstract=.*?\].*?\[\/abstract][\s|\n]*/ism", '', $text);
  1071. return $text;
  1072. }
  1073. /**
  1074. * @brief Returns the value of the "abstract" element
  1075. *
  1076. * @param string $text The text that maybe contains the element
  1077. * @param string $addon The addon for which the abstract is meant for
  1078. * @return string The abstract
  1079. */
  1080. function fetch_abstract($text, $addon = "") {
  1081. $abstract = "";
  1082. $abstracts = array();
  1083. $addon = strtolower($addon);
  1084. if (preg_match_all("/\[abstract=(.*?)\](.*?)\[\/abstract\]/ism",$text, $results, PREG_SET_ORDER))
  1085. foreach ($results AS $result)
  1086. $abstracts[strtolower($result[1])] = $result[2];
  1087. if (isset($abstracts[$addon]))
  1088. $abstract = $abstracts[$addon];
  1089. if ($abstract == "")
  1090. if (preg_match("/\[abstract\](.*?)\[\/abstract\]/ism",$text, $result))
  1091. $abstract = $result[1];
  1092. return $abstract;
  1093. }