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.
 
 
 
 
 
 

1345 line
48 KiB

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