]> git.mxchange.org Git - friendica.git/blob - include/html2bbcode.php
936bce338476fa26b265201bfd051a95b76e879e
[friendica.git] / include / html2bbcode.php
1 <?php
2 /**
3  * @file include/html2bbcode.php
4  * @brief Converter for HTML to BBCode
5  *
6  * Made by: ike@piratenpartei.de
7  * Originally made for the syncom project: http://wiki.piratenpartei.de/Syncom
8  *                                      https://github.com/annando/Syncom
9  */
10
11 use Friendica\Util\XML;
12
13 function node2bbcode(&$doc, $oldnode, $attributes, $startbb, $endbb)
14 {
15         do {
16                 $done = node2bbcodesub($doc, $oldnode, $attributes, $startbb, $endbb);
17         } while ($done);
18 }
19
20 function node2bbcodesub(&$doc, $oldnode, $attributes, $startbb, $endbb)
21 {
22         $savestart = str_replace('$', '\x01', $startbb);
23         $replace = false;
24
25         $xpath = new DomXPath($doc);
26
27         $list = $xpath->query("//".$oldnode);
28         foreach ($list as $oldNode) {
29                 $attr = array();
30                 if ($oldNode->attributes->length) {
31                         foreach ($oldNode->attributes as $attribute) {
32                                 $attr[$attribute->name] = $attribute->value;
33                         }
34                 }
35
36                 $replace = true;
37
38                 $startbb = $savestart;
39
40                 $i = 0;
41
42                 foreach ($attributes as $attribute => $value) {
43                         $startbb = str_replace('\x01'.++$i, '$1', $startbb);
44                         if (strpos('*'.$startbb, '$1') > 0) {
45                                 if ($replace && (@$attr[$attribute] != '')) {
46                                         $startbb = preg_replace($value, $startbb, $attr[$attribute], -1, $count);
47
48                                         // If nothing could be changed
49                                         if ($count == 0) {
50                                                 $replace = false;
51                                         }
52                                 } else {
53                                         $replace = false;
54                                 }
55                         } else {
56                                 if (@$attr[$attribute] != $value) {
57                                         $replace = false;
58                                 }
59                         }
60                 }
61
62                 if ($replace) {
63                         $StartCode = $oldNode->ownerDocument->createTextNode($startbb);
64                         $EndCode = $oldNode->ownerDocument->createTextNode($endbb);
65
66                         $oldNode->parentNode->insertBefore($StartCode, $oldNode);
67
68                         if ($oldNode->hasChildNodes()) {
69                                 foreach ($oldNode->childNodes as $child) {
70                                         $newNode = $child->cloneNode(true);
71                                         $oldNode->parentNode->insertBefore($newNode, $oldNode);
72                                 }
73                         }
74
75                         $oldNode->parentNode->insertBefore($EndCode, $oldNode);
76                         $oldNode->parentNode->removeChild($oldNode);
77                 }
78         }
79         return($replace);
80 }
81
82 function html2bbcode($message, $basepath = '')
83 {
84
85         $message = str_replace("\r", "", $message);
86
87         // Removing code blocks before the whitespace removal processing below
88         $codeblocks = [];
89         $message = preg_replace_callback(
90                 '#<pre><code(?: class="([^"]*)")?>(.*)</code></pre>#iUs',
91                 function ($matches) use (&$codeblocks) {
92                         $return = '[codeblock-' . count($codeblocks) . ']';
93
94                         $prefix = '[code]';
95                         if ($matches[1] != '') {
96                                 $prefix = '[code=' . $matches[1] . ']';
97                         }
98                         $codeblocks[] = $prefix . trim($matches[2]) . '[/code]';
99                         return $return;
100                 },
101                 $message
102         );
103
104         $message = str_replace(
105                 array(
106                         "<li><p>",
107                         "</p></li>",
108                 ),
109                 array(
110                         "<li>",
111                         "</li>",
112                 ),
113                 $message
114         );
115
116         // remove namespaces
117         $message = preg_replace('=<(\w+):(.+?)>=', '<removeme>', $message);
118         $message = preg_replace('=</(\w+):(.+?)>=', '</removeme>', $message);
119
120         $doc = new DOMDocument();
121         $doc->preserveWhiteSpace = false;
122
123         $message = mb_convert_encoding($message, 'HTML-ENTITIES', "UTF-8");
124
125         @$doc->loadHTML($message);
126
127         XML::deleteNode($doc, 'style');
128         XML::deleteNode($doc, 'head');
129         XML::deleteNode($doc, 'title');
130         XML::deleteNode($doc, 'meta');
131         XML::deleteNode($doc, 'xml');
132         XML::deleteNode($doc, 'removeme');
133
134         $xpath = new DomXPath($doc);
135         $list = $xpath->query("//pre");
136         foreach ($list as $node) {
137                 $node->nodeValue = str_replace("\n", "\r", $node->nodeValue);
138         }
139
140         $message = $doc->saveHTML();
141         $message = str_replace(array("\n<", ">\n", "\r", "\n", "\xC3\x82\xC2\xA0"), array("<", ">", "<br />", " ", ""), $message);
142         $message = preg_replace('= [\s]*=i', " ", $message);
143         @$doc->loadHTML($message);
144
145         node2bbcode($doc, 'html', array(), "", "");
146         node2bbcode($doc, 'body', array(), "", "");
147
148         // Outlook-Quote - Variant 1
149         node2bbcode($doc, 'p', array('class'=>'MsoNormal', 'style'=>'margin-left:35.4pt'), '[quote]', '[/quote]');
150
151         // Outlook-Quote - Variant 2
152         node2bbcode($doc, 'div', array('style'=>'border:none;border-left:solid blue 1.5pt;padding:0cm 0cm 0cm 4.0pt'), '[quote]', '[/quote]');
153
154         // MyBB-Stuff
155         node2bbcode($doc, 'span', array('style'=>'text-decoration: underline;'), '[u]', '[/u]');
156         node2bbcode($doc, 'span', array('style'=>'font-style: italic;'), '[i]', '[/i]');
157         node2bbcode($doc, 'span', array('style'=>'font-weight: bold;'), '[b]', '[/b]');
158
159         /*node2bbcode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[font=$1][size=$2][color=$3]', '[/color][/size][/font]');
160         node2bbcode($doc, 'font', array('size'=>'/(\d+)/', 'color'=>'/(.+)/'), '[size=$1][color=$2]', '[/color][/size]');
161         node2bbcode($doc, 'font', array('face'=>'/([\w ]+)/', 'size'=>'/(.+)/'), '[font=$1][size=$2]', '[/size][/font]');
162         node2bbcode($doc, 'font', array('face'=>'/([\w ]+)/', 'color'=>'/(.+)/'), '[font=$1][color=$3]', '[/color][/font]');
163         node2bbcode($doc, 'font', array('face'=>'/([\w ]+)/'), '[font=$1]', '[/font]');
164         node2bbcode($doc, 'font', array('size'=>'/(\d+)/'), '[size=$1]', '[/size]');
165         node2bbcode($doc, 'font', array('color'=>'/(.+)/'), '[color=$1]', '[/color]');
166         */
167         // Untested
168         //node2bbcode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*font-family:\s*(.+?)[,;].*color:\s*(.+?)[,;].*/'), '[size=$1][font=$2][color=$3]', '[/color][/font][/size]');
169         //node2bbcode($doc, 'span', array('style'=>'/.*font-size:\s*(\d+)[,;].*/'), '[size=$1]', '[/size]');
170         //node2bbcode($doc, 'span', array('style'=>'/.*font-size:\s*(.+?)[,;].*/'), '[size=$1]', '[/size]');
171
172         node2bbcode($doc, 'span', array('style'=>'/.*color:\s*(.+?)[,;].*/'), '[color="$1"]', '[/color]');
173
174         //node2bbcode($doc, 'span', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
175
176         //node2bbcode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)pt.*/'), '[font=$1][size=$2]', '[/size][/font]');
177         //node2bbcode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*font-size:\s*(\d+?)px.*/'), '[font=$1][size=$2]', '[/size][/font]');
178         //node2bbcode($doc, 'div', array('style'=>'/.*font-family:\s*(.+?)[,;].*/'), '[font=$1]', '[/font]');
179
180         // Importing the classes - interesting for importing of posts from third party networks that were exported from friendica
181         // Test
182         //node2bbcode($doc, 'span', array('class'=>'/([\w ]+)/'), '[class=$1]', '[/class]');
183         node2bbcode($doc, 'span', array('class'=>'type-link'), '[class=type-link]', '[/class]');
184         node2bbcode($doc, 'span', array('class'=>'type-video'), '[class=type-video]', '[/class]');
185
186         node2bbcode($doc, 'strong', array(), '[b]', '[/b]');
187         node2bbcode($doc, 'em', array(), '[i]', '[/i]');
188         node2bbcode($doc, 'b', array(), '[b]', '[/b]');
189         node2bbcode($doc, 'i', array(), '[i]', '[/i]');
190         node2bbcode($doc, 'u', array(), '[u]', '[/u]');
191
192         node2bbcode($doc, 'big', array(), "[size=large]", "[/size]");
193         node2bbcode($doc, 'small', array(), "[size=small]", "[/size]");
194
195         node2bbcode($doc, 'blockquote', array(), '[quote]', '[/quote]');
196
197         node2bbcode($doc, 'br', array(), "\n", '');
198
199         node2bbcode($doc, 'p', array('class'=>'MsoNormal'), "\n", "");
200         node2bbcode($doc, 'div', array('class'=>'MsoNormal'), "\r", "");
201
202         node2bbcode($doc, 'span', array(), "", "");
203
204         node2bbcode($doc, 'span', array(), "", "");
205         node2bbcode($doc, 'pre', array(), "", "");
206
207         node2bbcode($doc, 'div', array(), "\r", "\r");
208         node2bbcode($doc, 'p', array(), "\n", "\n");
209
210         node2bbcode($doc, 'ul', array(), "[list]", "[/list]");
211         node2bbcode($doc, 'ol', array(), "[list=1]", "[/list]");
212         node2bbcode($doc, 'li', array(), "[*]", "");
213
214         node2bbcode($doc, 'hr', array(), "[hr]", "");
215
216         node2bbcode($doc, 'table', array(), "", "");
217         node2bbcode($doc, 'tr', array(), "\n", "");
218         node2bbcode($doc, 'td', array(), "\t", "");
219         //node2bbcode($doc, 'table', array(), "[table]", "[/table]");
220         //node2bbcode($doc, 'th', array(), "[th]", "[/th]");
221         //node2bbcode($doc, 'tr', array(), "[tr]", "[/tr]");
222         //node2bbcode($doc, 'td', array(), "[td]", "[/td]");
223
224         //node2bbcode($doc, 'h1', array(), "\n\n[size=xx-large][b]", "[/b][/size]\n");
225         //node2bbcode($doc, 'h2', array(), "\n\n[size=x-large][b]", "[/b][/size]\n");
226         //node2bbcode($doc, 'h3', array(), "\n\n[size=large][b]", "[/b][/size]\n");
227         //node2bbcode($doc, 'h4', array(), "\n\n[size=medium][b]", "[/b][/size]\n");
228         //node2bbcode($doc, 'h5', array(), "\n\n[size=small][b]", "[/b][/size]\n");
229         //node2bbcode($doc, 'h6', array(), "\n\n[size=x-small][b]", "[/b][/size]\n");
230
231         node2bbcode($doc, 'h1', array(), "\n\n[h1]", "[/h1]\n");
232         node2bbcode($doc, 'h2', array(), "\n\n[h2]", "[/h2]\n");
233         node2bbcode($doc, 'h3', array(), "\n\n[h3]", "[/h3]\n");
234         node2bbcode($doc, 'h4', array(), "\n\n[h4]", "[/h4]\n");
235         node2bbcode($doc, 'h5', array(), "\n\n[h5]", "[/h5]\n");
236         node2bbcode($doc, 'h6', array(), "\n\n[h6]", "[/h6]\n");
237
238         node2bbcode($doc, 'a', array('href'=>'/mailto:(.+)/'), '[mail=$1]', '[/mail]');
239         node2bbcode($doc, 'a', array('href'=>'/(.+)/'), '[url=$1]', '[/url]');
240
241         node2bbcode($doc, 'img', array('src'=>'/(.+)/', 'width'=>'/(\d+)/', 'height'=>'/(\d+)/'), '[img=$2x$3]$1', '[/img]');
242         node2bbcode($doc, 'img', array('src'=>'/(.+)/'), '[img]$1', '[/img]');
243
244
245         node2bbcode($doc, 'video', array('src'=>'/(.+)/'), '[video]$1', '[/video]');
246         node2bbcode($doc, 'audio', array('src'=>'/(.+)/'), '[audio]$1', '[/audio]');
247         node2bbcode($doc, 'iframe', array('src'=>'/(.+)/'), '[iframe]$1', '[/iframe]');
248
249         node2bbcode($doc, 'key', array(), '[code]', '[/code]');
250         node2bbcode($doc, 'code', array(), '[code]', '[/code]');
251
252         $message = $doc->saveHTML();
253
254         // I'm removing something really disturbing
255         // Don't know exactly what it is
256         $message = str_replace(chr(194).chr(160), ' ', $message);
257
258         $message = str_replace("&nbsp;", " ", $message);
259
260         // removing multiple DIVs
261         $message = preg_replace('=\r *\r=i', "\n", $message);
262         $message = str_replace("\r", "\n", $message);
263
264         call_hooks('html2bbcode', $message);
265
266         $message = strip_tags($message);
267
268         $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
269
270         $message = str_replace(array("<"), array("&lt;"), $message);
271
272         // remove quotes if they don't make sense
273         $message = preg_replace('=\[/quote\][\s]*\[quote\]=i', "\n", $message);
274
275         $message = preg_replace('=\[quote\]\s*=i', "[quote]", $message);
276         $message = preg_replace('=\s*\[/quote\]=i', "[/quote]", $message);
277
278         do {
279                 $oldmessage = $message;
280                 $message = str_replace("\n \n", "\n\n", $message);
281         } while ($oldmessage != $message);
282
283         do {
284                 $oldmessage = $message;
285                 $message = str_replace("\n\n\n", "\n\n", $message);
286         } while ($oldmessage != $message);
287
288         do {
289                 $oldmessage = $message;
290                 $message = str_replace(
291                         array(
292                                 "[/size]\n\n",
293                                 "\n[hr]",
294                                 "[hr]\n",
295                                 "\n[list",
296                                 "[/list]\n",
297                                 "\n[/",
298                                 "[list]\n",
299                                 "[list=1]\n",
300                                 "\n[*]"),
301                         array(
302                                 "[/size]\n",
303                                 "[hr]",
304                                 "[hr]",
305                                 "[list",
306                                 "[/list]",
307                                 "[/",
308                                 "[list]",
309                                 "[list=1]",
310                                 "[*]"),
311                         $message
312                 );
313         } while ($message != $oldmessage);
314
315         $message = str_replace(
316                 array('[b][b]', '[/b][/b]', '[i][i]', '[/i][/i]'),
317                 array('[b]', '[/b]', '[i]', '[/i]'),
318                 $message
319         );
320
321         // Handling Yahoo style of mails
322         $message = str_replace('[hr][b]From:[/b]', '[quote][b]From:[/b]', $message);
323
324         // Restore code blocks
325         $message = preg_replace_callback(
326                 '#\[codeblock-([0-9]+)\]#iU',
327                 function ($matches) use ($codeblocks) {
328                         $return = '';
329                         if (isset($codeblocks[intval($matches[1])])) {
330                                 $return = $codeblocks[$matches[1]];
331                         }
332                         return $return;
333                 },
334                 $message
335         );
336
337         $message = trim($message);
338
339         if ($basepath != '') {
340                 $message = addHostname($message, $basepath);
341         }
342
343         return $message;
344 }
345
346 /**
347  * @brief Sub function to complete incomplete URL
348  *
349  * @param array  $matches  Result of preg_replace_callback
350  * @param string $basepath Basepath that is used to complete the URL
351  *
352  * @return string The expanded URL
353  */
354 function addHostnameSub($matches, $basepath)
355 {
356         $base = parse_url($basepath);
357         unset($base['query']);
358         unset($base['fragment']);
359
360         $link = $matches[0];
361         $url = $matches[1];
362
363         $parts = array_merge($base, parse_url($url));
364         $url2 = unParseUrl($parts);
365
366         return str_replace($url, $url2, $link);
367 }
368
369 /**
370  * @brief Complete incomplete URLs in BBCode
371  *
372  * @param string $body     Body with URLs
373  * @param string $basepath Basepath that is used to complete the URL
374  *
375  * @return string Body with expanded URLs
376  */
377 function addHostname($body, $basepath)
378 {
379         $URLSearchString = "^\[\]";
380
381         $matches = array("/\[url\=([$URLSearchString]*)\].*?\[\/url\]/ism",
382                         "/\[url\]([$URLSearchString]*)\[\/url\]/ism",
383                         "/\[img\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
384                         "/\[img\](.*?)\[\/img\]/ism",
385                         "/\[zmg\=[0-9]*x[0-9]*\](.*?)\[\/img\]/ism",
386                         "/\[zmg\](.*?)\[\/zmg\]/ism",
387                         "/\[video\](.*?)\[\/video\]/ism",
388                         "/\[audio\](.*?)\[\/audio\]/ism",
389                         );
390
391         foreach ($matches as $match) {
392                 $body = preg_replace_callback(
393                         $match,
394                         function ($match) use ($basepath) {
395                                 return addHostnameSub($match, $basepath);
396                         },
397                         $body
398                 );
399         }
400         return $body;
401 }