]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/BBCode.php
Review update
[friendica.git] / src / Content / Text / BBCode.php
1 <?php
2 /**
3  * @file src/Content/Text/BBCode.php
4  */
5 namespace Friendica\Content\Text;
6
7 use Friendica\App;
8 use Friendica\Content\Text\Plaintext;
9 use Friencica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Object\Image;
14 use Friendica\Util\ParseUrl;
15
16 require_once "include/bbcode.php";
17 require_once "include/html2plain.php";
18
19 class BBCode
20 {
21         /**
22          * @brief Fetches attachment data that were generated the old way
23          *
24          * @param string $body Message body
25          * @return array
26          * 'type' -> Message type ("link", "video", "photo")
27          * 'text' -> Text before the shared message
28          * 'after' -> Text after the shared message
29          * 'image' -> Preview image of the message
30          * 'url' -> Url to the attached message
31          * 'title' -> Title of the attachment
32          * 'description' -> Description of the attachment
33          */
34         private static function getOldAttachmentData($body)
35         {
36                 $post = [];
37
38                 // Simplify image codes
39                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
40
41                 if (preg_match_all("(\[class=(.*?)\](.*?)\[\/class\])ism", $body, $attached, PREG_SET_ORDER)) {
42                         foreach ($attached as $data) {
43                                 if (!in_array($data[1], ["type-link", "type-video", "type-photo"])) {
44                                         continue;
45                                 }
46
47                                 $post["type"] = substr($data[1], 5);
48
49                                 $pos = strpos($body, $data[0]);
50                                 if ($pos > 0) {
51                                         $post["text"] = trim(substr($body, 0, $pos));
52                                         $post["after"] = trim(substr($body, $pos + strlen($data[0])));
53                                 } else {
54                                         $post["text"] = trim(str_replace($data[0], "", $body));
55                                 }
56
57                                 $attacheddata = $data[2];
58
59                                 $URLSearchString = "^\[\]";
60
61                                 if (preg_match("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $attacheddata, $matches)) {
62
63                                         $picturedata = Image::getInfoFromURL($matches[1]);
64
65                                         if (($picturedata[0] >= 500) && ($picturedata[0] >= $picturedata[1])) {
66                                                 $post["image"] = $matches[1];
67                                         } else {
68                                                 $post["preview"] = $matches[1];
69                                         }
70                                 }
71
72                                 if (preg_match("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", $attacheddata, $matches)) {
73                                         $post["url"] = $matches[1];
74                                         $post["title"] = $matches[2];
75                                 }
76                                 if (($post["url"] == "") && (in_array($post["type"], ["link", "video"]))
77                                         && preg_match("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $attacheddata, $matches)) {
78                                         $post["url"] = $matches[1];
79                                 }
80
81                                 // Search for description
82                                 if (preg_match("/\[quote\](.*?)\[\/quote\]/ism", $attacheddata, $matches)) {
83                                         $post["description"] = $matches[1];
84                                 }
85                         }
86                 }
87                 return $post;
88         }
89
90         /**
91          * @brief Fetches attachment data that were generated with the "attachment" element
92          *
93          * @param string $body Message body
94          * @return array
95          * 'type' -> Message type ("link", "video", "photo")
96          * 'text' -> Text before the shared message
97          * 'after' -> Text after the shared message
98          * 'image' -> Preview image of the message
99          * 'url' -> Url to the attached message
100          * 'title' -> Title of the attachment
101          * 'description' -> Description of the attachment
102          */
103         public static function getAttachmentData($body)
104         {
105                 $data = [];
106
107                 if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
108                         return self::getOldAttachmentData($body);
109                 }
110
111                 $attributes = $match[2];
112
113                 $data["text"] = trim($match[1]);
114
115                 $type = "";
116                 preg_match("/type='(.*?)'/ism", $attributes, $matches);
117                 if (x($matches, 1)) {
118                         $type = strtolower($matches[1]);
119                 }
120
121                 preg_match('/type="(.*?)"/ism', $attributes, $matches);
122                 if (x($matches, 1)) {
123                         $type = strtolower($matches[1]);
124                 }
125
126                 if ($type == "") {
127                         return [];
128                 }
129
130                 if (!in_array($type, ["link", "audio", "photo", "video"])) {
131                         return [];
132                 }
133
134                 if ($type != "") {
135                         $data["type"] = $type;
136                 }
137
138                 $url = "";
139                 preg_match("/url='(.*?)'/ism", $attributes, $matches);
140                 if (x($matches, 1)) {
141                         $url = $matches[1];
142                 }
143
144                 preg_match('/url="(.*?)"/ism', $attributes, $matches);
145                 if (x($matches, 1)) {
146                         $url = $matches[1];
147                 }
148
149                 if ($url != "") {
150                         $data["url"] = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
151                 }
152
153                 $title = "";
154                 preg_match("/title='(.*?)'/ism", $attributes, $matches);
155                 if (x($matches, 1)) {
156                         $title = $matches[1];
157                 }
158
159                 preg_match('/title="(.*?)"/ism', $attributes, $matches);
160                 if (x($matches, 1)) {
161                         $title = $matches[1];
162                 }
163
164                 if ($title != "") {
165                         $title = bbcode(html_entity_decode($title, ENT_QUOTES, 'UTF-8'), false, false, true);
166                         $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
167                         $title = str_replace(["[", "]"], ["&#91;", "&#93;"], $title);
168                         $data["title"] = $title;
169                 }
170
171                 $image = "";
172                 preg_match("/image='(.*?)'/ism", $attributes, $matches);
173                 if (x($matches, 1)) {
174                         $image = $matches[1];
175                 }
176
177                 preg_match('/image="(.*?)"/ism', $attributes, $matches);
178                 if (x($matches, 1)) {
179                         $image = $matches[1];
180                 }
181
182                 if ($image != "") {
183                         $data["image"] = html_entity_decode($image, ENT_QUOTES, 'UTF-8');
184                 }
185
186                 $preview = "";
187                 preg_match("/preview='(.*?)'/ism", $attributes, $matches);
188                 if (x($matches, 1)) {
189                         $preview = $matches[1];
190                 }
191
192                 preg_match('/preview="(.*?)"/ism', $attributes, $matches);
193                 if (x($matches, 1)) {
194                         $preview = $matches[1];
195                 }
196
197                 if ($preview != "") {
198                         $data["preview"] = html_entity_decode($preview, ENT_QUOTES, 'UTF-8');
199                 }
200
201                 $data["description"] = trim($match[3]);
202
203                 $data["after"] = trim($match[4]);
204
205                 return $data;
206         }
207
208         public static function getAttachedData($body, $item = [])
209         {
210                 /*
211                 - text:
212                 - type: link, video, photo
213                 - title:
214                 - url:
215                 - image:
216                 - description:
217                 - (thumbnail)
218                 */
219
220                 $has_title = !empty($item['title']);
221                 $plink = (!empty($item['plink']) ? $item['plink'] : '');
222                 $post = self::getAttachmentData($body);
223
224                 // if nothing is found, it maybe having an image.
225                 if (!isset($post["type"])) {
226                         // Simplify image codes
227                         $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
228
229                         $URLSearchString = "^\[\]";
230                         if (preg_match_all("(\[url=([$URLSearchString]*)\]\s*\[img\]([$URLSearchString]*)\[\/img\]\s*\[\/url\])ism", $body, $pictures, PREG_SET_ORDER)) {
231                                 if ((count($pictures) == 1) && !$has_title) {
232                                         // Checking, if the link goes to a picture
233                                         $data = ParseUrl::getSiteinfoCached($pictures[0][1], true);
234
235                                         // Workaround:
236                                         // Sometimes photo posts to the own album are not detected at the start.
237                                         // So we seem to cannot use the cache for these cases. That's strange.
238                                         if (($data["type"] != "photo") && strstr($pictures[0][1], "/photos/")) {
239                                                 $data = ParseUrl::getSiteinfo($pictures[0][1], true);
240                                         }
241
242                                         if ($data["type"] == "photo") {
243                                                 $post["type"] = "photo";
244                                                 if (isset($data["images"][0])) {
245                                                         $post["image"] = $data["images"][0]["src"];
246                                                         $post["url"] = $data["url"];
247                                                 } else {
248                                                         $post["image"] = $data["url"];
249                                                 }
250
251                                                 $post["preview"] = $pictures[0][2];
252                                                 $post["text"] = str_replace($pictures[0][0], "", $body);
253                                         } else {
254                                                 $imgdata = Image::getInfoFromURL($pictures[0][1]);
255                                                 if (substr($imgdata["mime"], 0, 6) == "image/") {
256                                                         $post["type"] = "photo";
257                                                         $post["image"] = $pictures[0][1];
258                                                         $post["preview"] = $pictures[0][2];
259                                                         $post["text"] = str_replace($pictures[0][0], "", $body);
260                                                 }
261                                         }
262                                 } elseif (count($pictures) > 0) {
263                                         $post["type"] = "link";
264                                         $post["url"] = $plink;
265                                         $post["image"] = $pictures[0][2];
266                                         $post["text"] = $body;
267                                 }
268                         } elseif (preg_match_all("(\[img\]([$URLSearchString]*)\[\/img\])ism", $body, $pictures, PREG_SET_ORDER)) {
269                                 if ((count($pictures) == 1) && !$has_title) {
270                                         $post["type"] = "photo";
271                                         $post["image"] = $pictures[0][1];
272                                         $post["text"] = str_replace($pictures[0][0], "", $body);
273                                 } elseif (count($pictures) > 0) {
274                                         $post["type"] = "link";
275                                         $post["url"] = $plink;
276                                         $post["image"] = $pictures[0][1];
277                                         $post["text"] = $body;
278                                 }
279                         }
280
281                         // Test for the external links
282                         preg_match_all("(\[url\]([$URLSearchString]*)\[\/url\])ism", $body, $links1, PREG_SET_ORDER);
283                         preg_match_all("(\[url\=([$URLSearchString]*)\].*?\[\/url\])ism", $body, $links2, PREG_SET_ORDER);
284
285                         $links = array_merge($links1, $links2);
286
287                         // If there is only a single one, then use it.
288                         // This should cover link posts via API.
289                         if ((count($links) == 1) && !isset($post["preview"]) && !$has_title) {
290                                 $post["type"] = "link";
291                                 $post["text"] = trim($body);
292                                 $post["url"] = $links[0][1];
293                         }
294
295                         // Now count the number of external media links
296                         preg_match_all("(\[vimeo\](.*?)\[\/vimeo\])ism", $body, $links1, PREG_SET_ORDER);
297                         preg_match_all("(\[youtube\\](.*?)\[\/youtube\\])ism", $body, $links2, PREG_SET_ORDER);
298                         preg_match_all("(\[video\\](.*?)\[\/video\\])ism", $body, $links3, PREG_SET_ORDER);
299                         preg_match_all("(\[audio\\](.*?)\[\/audio\\])ism", $body, $links4, PREG_SET_ORDER);
300
301                         // Add them to the other external links
302                         $links = array_merge($links, $links1, $links2, $links3, $links4);
303
304                         // Are there more than one?
305                         if (count($links) > 1) {
306                                 // The post will be the type "text", which means a blog post
307                                 unset($post["type"]);
308                                 $post["url"] = $plink;
309                         }
310
311                         if (!isset($post["type"])) {
312                                 $post["type"] = "text";
313                                 $post["text"] = trim($body);
314                         }
315                 } elseif (isset($post["url"]) && ($post["type"] == "video")) {
316                         $data = ParseUrl::getSiteinfoCached($post["url"], true);
317
318                         if (isset($data["images"][0])) {
319                                 $post["image"] = $data["images"][0]["src"];
320                         }
321                 }
322
323                 return $post;
324         }
325
326         /**
327          * @brief Convert a message into plaintext for connectors to other networks
328          *
329          * @param array $b The message array that is about to be posted
330          * @param int $limit The maximum number of characters when posting to that network
331          * @param bool $includedlinks Has an attached link to be included into the message?
332          * @param int $htmlmode This triggers the behaviour of the bbcode conversion
333          * @param string $target_network Name of the network where the post should go to.
334          *
335          * @return string The converted message
336          */
337         public static function toPlaintext($b, $limit = 0, $includedlinks = false, $htmlmode = 2, $target_network = "")
338         {
339                 // Remove the hash tags
340                 $URLSearchString = "^\[\]";
341                 $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $b["body"]);
342
343                 // Add an URL element if the text contains a raw link
344                 $body = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url]$2[/url]', $body);
345
346                 // Remove the abstract
347                 $body = remove_abstract($body);
348
349                 // At first look at data that is attached via "type-..." stuff
350                 // This will hopefully replaced with a dedicated bbcode later
351                 //$post = self::getAttachedData($b["body"]);
352                 $post = self::getAttachedData($body, $b);
353
354                 if (($b["title"] != "") && ($post["text"] != "")) {
355                         $post["text"] = trim($b["title"]."\n\n".$post["text"]);
356                 } elseif ($b["title"] != "") {
357                         $post["text"] = trim($b["title"]);
358                 }
359
360                 $abstract = "";
361
362                 // Fetch the abstract from the given target network
363                 if ($target_network != "") {
364                         $default_abstract = fetch_abstract($b["body"]);
365                         $abstract = fetch_abstract($b["body"], $target_network);
366
367                         // If we post to a network with no limit we only fetch
368                         // an abstract exactly for this network
369                         if (($limit == 0) && ($abstract == $default_abstract)) {
370                                 $abstract = "";
371                         }
372                 } else {// Try to guess the correct target network
373                         switch ($htmlmode) {
374                                 case 8:
375                                         $abstract = fetch_abstract($b["body"], NETWORK_TWITTER);
376                                         break;
377                                 case 7:
378                                         $abstract = fetch_abstract($b["body"], NETWORK_STATUSNET);
379                                         break;
380                                 case 6:
381                                         $abstract = fetch_abstract($b["body"], NETWORK_APPNET);
382                                         break;
383                                 default: // We don't know the exact target.
384                                         // We fetch an abstract since there is a posting limit.
385                                         if ($limit > 0) {
386                                                 $abstract = fetch_abstract($b["body"]);
387                                         }
388                         }
389                 }
390
391                 if ($abstract != "") {
392                         $post["text"] = $abstract;
393
394                         if ($post["type"] == "text") {
395                                 $post["type"] = "link";
396                                 $post["url"] = $b["plink"];
397                         }
398                 }
399
400                 $html = bbcode($post["text"].$post["after"], false, false, $htmlmode);
401                 $msg = html2plain($html, 0, true);
402                 $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8'));
403
404                 $link = "";
405                 if ($includedlinks) {
406                         if ($post["type"] == "link") {
407                                 $link = $post["url"];
408                         } elseif ($post["type"] == "text") {
409                                 $link = $post["url"];
410                         } elseif ($post["type"] == "video") {
411                                 $link = $post["url"];
412                         } elseif ($post["type"] == "photo") {
413                                 $link = $post["image"];
414                         }
415
416                         if (($msg == "") && isset($post["title"])) {
417                                 $msg = trim($post["title"]);
418                         }
419
420                         if (($msg == "") && isset($post["description"])) {
421                                 $msg = trim($post["description"]);
422                         }
423
424                         // If the link is already contained in the post, then it neeedn't to be added again
425                         // But: if the link is beyond the limit, then it has to be added.
426                         if (($link != "") && strstr($msg, $link)) {
427                                 $pos = strpos($msg, $link);
428
429                                 // Will the text be shortened in the link?
430                                 // Or is the link the last item in the post?
431                                 if (($limit > 0) && ($pos < $limit) && (($pos + 23 > $limit) || ($pos + strlen($link) == strlen($msg)))) {
432                                         $msg = trim(str_replace($link, "", $msg));
433                                 } elseif (($limit == 0) || ($pos < $limit)) {
434                                         // The limit has to be increased since it will be shortened - but not now
435                                         // Only do it with Twitter (htmlmode = 8)
436                                         if (($limit > 0) && (strlen($link) > 23) && ($htmlmode == 8)) {
437                                                 $limit = $limit - 23 + strlen($link);
438                                         }
439
440                                         $link = "";
441
442                                         if ($post["type"] == "text") {
443                                                 unset($post["url"]);
444                                         }
445                                 }
446                         }
447                 }
448
449                 if ($limit > 0) {
450                         // Reduce multiple spaces
451                         // When posted to a network with limited space, we try to gain space where possible
452                         while (strpos($msg, "  ") !== false) {
453                                 $msg = str_replace("  ", " ", $msg);
454                         }
455
456                         // Twitter is using its own limiter, so we always assume that shortened links will have this length
457                         if (iconv_strlen($link, "UTF-8") > 0) {
458                                 $limit = $limit - 23;
459                         }
460
461                         if (iconv_strlen($msg, "UTF-8") > $limit) {
462                                 if (($post["type"] == "text") && isset($post["url"])) {
463                                         $post["url"] = $b["plink"];
464                                 } elseif (!isset($post["url"])) {
465                                         $limit = $limit - 23;
466                                         $post["url"] = $b["plink"];
467                                 // Which purpose has this line? It is now uncommented, but left as a reminder
468                                 //} elseif (strpos($b["body"], "[share") !== false) {
469                                 //      $post["url"] = $b["plink"];
470                                 } elseif (PConfig::get($b["uid"], "system", "no_intelligent_shortening")) {
471                                         $post["url"] = $b["plink"];
472                                 }
473                                 $msg = Plaintext::shorten($msg, $limit);
474                         }
475                 }
476
477                 $post["text"] = trim($msg);
478
479                 return($post);
480         }
481
482         public static function scaleExternalImages($srctext, $include_link = true, $scale_replace = false)
483         {
484                 // Suppress "view full size"
485                 if (intval(Config::get('system', 'no_view_full_size'))) {
486                         $include_link = false;
487                 }
488
489                 // Picture addresses can contain special characters
490                 $s = htmlspecialchars_decode($srctext);
491
492                 $matches = null;
493                 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
494                 if ($c) {
495                         foreach ($matches as $mtch) {
496                                 logger('scale_external_image: ' . $mtch[1]);
497
498                                 $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
499                                 if (stristr($mtch[1], $hostname)) {
500                                         continue;
501                                 }
502
503                                 // $scale_replace, if passed, is an array of two elements. The
504                                 // first is the name of the full-size image. The second is the
505                                 // name of a remote, scaled-down version of the full size image.
506                                 // This allows Friendica to display the smaller remote image if
507                                 // one exists, while still linking to the full-size image
508                                 if ($scale_replace) {
509                                         $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
510                                 } else {
511                                         $scaled = $mtch[1];
512                                 }
513                                 $i = self::fetchURL($scaled);
514                                 if (! $i) {
515                                         return $srctext;
516                                 }
517
518                                 // guess mimetype from headers or filename
519                                 $type = Image::guessType($mtch[1], true);
520
521                                 if ($i) {
522                                         $Image = new Image($i, $type);
523                                         if ($Image->isValid()) {
524                                                 $orig_width = $Image->getWidth();
525                                                 $orig_height = $Image->getHeight();
526
527                                                 if ($orig_width > 640 || $orig_height > 640) {
528                                                         $Image->scaleDown(640);
529                                                         $new_width = $Image->getWidth();
530                                                         $new_height = $Image->getHeight();
531                                                         logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
532                                                         $s = str_replace(
533                                                                 $mtch[0],
534                                                                 '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
535                                                                 . "\n" . (($include_link)
536                                                                         ? '[url=' . $mtch[1] . ']' . L10n::t('view full size') . '[/url]' . "\n"
537                                                                         : ''),
538                                                                 $s
539                                                         );
540                                                         logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
541                                                 }
542                                         }
543                                 }
544                         }
545                 }
546
547                 // replace the special char encoding
548                 $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
549                 return $s;
550         }
551 }