00a2adcbb9301260c93462cac4515b6ea11dd3b2
[citadel.git] / webcit / html2html.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup HTML2HTML Output an HTML message, modifying it slightly to make sure it plays nice
6  * with the rest of our web framework.
7  * \ingroup WebcitHttpServer
8  */
9 /*@{*/
10 #include "webcit.h"
11 #include "vcard.h"
12 #include "webserver.h"
13
14
15 /**
16  * \brief       Strip surrounding single or double quotes from a string.
17  *
18  * \param s     String to be stripped.
19  */
20 void stripquotes(char *s)
21 {
22         int len;
23
24         if (!s) return;
25
26         len = strlen(s);
27         if (len < 2) return;
28
29         if ( ( (s[0] == '\"') && (s[len-1] == '\"') ) || ( (s[0] == '\'') && (s[len-1] == '\'') ) ) {
30                 s[len-1] = 0;
31                 strcpy(s, &s[1]);
32         }
33 }
34
35
36 /**
37  * \brief Check to see if a META tag has overridden the declared MIME character set.
38  *
39  * \param charset               Character set name (left unchanged if we don't do anything)
40  * \param meta_http_equiv       Content of the "http-equiv" portion of the META tag
41  * \param meta_content          Content of the "content" portion of the META tag
42  */
43 void extract_charset_from_meta(char *charset, char *meta_http_equiv, char *meta_content)
44 {
45         char *ptr;
46         char buf[64];
47
48         if (!charset) return;
49         if (!meta_http_equiv) return;
50         if (!meta_content) return;
51
52
53         if (strcasecmp(meta_http_equiv, "Content-type")) return;
54
55         ptr = strchr(meta_content, ';');
56         if (!ptr) return;
57
58         safestrncpy(buf, ++ptr, sizeof buf);
59         striplt(buf);
60         if (!strncasecmp(buf, "charset=", 8)) {
61                 strcpy(charset, &buf[8]);
62         }
63 }
64
65
66
67 /**
68  * \brief Sanitize and enhance an HTML message for display.
69  *        Also convert weird character sets to UTF-8 if necessary.
70  *
71  * \param supplied_charset the input charset as declared in the MIME headers
72  */
73 void output_html(char *supplied_charset, int treat_as_wiki) {
74         char buf[SIZ];
75         char *msg;
76         char *ptr;
77         char *msgstart;
78         char *msgend;
79         char *converted_msg;
80         int buffer_length = 1;
81         int line_length = 0;
82         int content_length = 0;
83         int output_length = 0;
84         char new_window[SIZ];
85         int brak = 0;
86         int alevel = 0;
87         int i;
88         int linklen;
89         char charset[128];
90 #ifdef HAVE_ICONV
91         iconv_t ic = (iconv_t)(-1) ;
92         char *ibuf;                   /**< Buffer of characters to be converted */
93         char *obuf;                   /**< Buffer for converted characters      */
94         size_t ibuflen;               /**< Length of input buffer               */
95         size_t obuflen;               /**< Length of output buffer              */
96         char *osav;                   /**< Saved pointer to output buffer       */
97 #endif
98
99         safestrncpy(charset, supplied_charset, sizeof charset);
100         msg = strdup("");
101         sprintf(new_window, "<a target=\"%s\" href=", TARGET);
102
103         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
104                 line_length = strlen(buf);
105                 buffer_length = content_length + line_length + 2;
106                 msg = realloc(msg, buffer_length);
107                 if (msg == NULL) {
108                         wprintf("<b>");
109                         wprintf(_("realloc() error! couldn't get %d bytes: %s"),
110                                 buffer_length + 1,
111                                 strerror(errno));
112                         wprintf("</b><br /><br />\n");
113                         return;
114                 }
115                 strcpy(&msg[content_length], buf);
116                 content_length += line_length;
117                 strcpy(&msg[content_length], "\n");
118                 content_length += 1;
119         }
120
121         /** Do a first pass to isolate the message body */
122         ptr = msg;
123         msgstart = msg;
124         msgend = &msg[content_length];
125
126         while (ptr < msgend) {
127
128                 /** Advance to next tag */
129                 ptr = strchr(ptr, '<');
130                 if ((ptr == NULL) || (ptr >= msgend)) break;
131                 ++ptr;
132                 if ((ptr == NULL) || (ptr >= msgend)) break;
133
134                 /**
135                  *  Look for META tags.  Some messages (particularly in
136                  *  Asian locales) illegally declare a message's character
137                  *  set in the HTML instead of in the MIME headers.  This
138                  *  is wrong but we have to work around it anyway.
139                  */
140                 if (!strncasecmp(ptr, "META", 4)) {
141
142                         char *meta_start;
143                         char *meta_end;
144                         int meta_length;
145                         char *meta;
146                         char *meta_http_equiv;
147                         char *meta_content;
148                         char *spaceptr;
149
150                         meta_start = &ptr[4];
151                         meta_end = strchr(ptr, '>');
152                         if ((meta_end != NULL) && (meta_end <= msgend)) {
153                                 meta_length = meta_end - meta_start + 1;
154                                 meta = malloc(meta_length + 1);
155                                 safestrncpy(meta, meta_start, meta_length);
156                                 meta[meta_length] = 0;
157                                 striplt(meta);
158                                 if (!strncasecmp(meta, "HTTP-EQUIV=", 11)) {
159                                         meta_http_equiv = strdup(&meta[11]);
160                                         spaceptr = strchr(meta_http_equiv, ' ');
161                                         if (spaceptr != NULL) {
162                                                 *spaceptr = 0;
163                                                 meta_content = strdup(++spaceptr);
164                                                 if (!strncasecmp(meta_content, "content=", 8)) {
165                                                         strcpy(meta_content, &meta_content[8]);
166                                                         stripquotes(meta_http_equiv);
167                                                         stripquotes(meta_content);
168                                                         extract_charset_from_meta(charset,
169                                                                 meta_http_equiv, meta_content);
170                                                 }
171                                                 free(meta_content);
172                                         }
173                                         free(meta_http_equiv);
174                                 }
175                                 free(meta);
176                         }
177                 }
178
179                 /**
180                  * Any of these tags cause everything up to and including
181                  * the tag to be removed.
182                  */     
183                 if ( (!strncasecmp(ptr, "HTML", 4))
184                    ||(!strncasecmp(ptr, "HEAD", 4))
185                    ||(!strncasecmp(ptr, "/HEAD", 5))
186                    ||(!strncasecmp(ptr, "BODY", 4)) ) {
187                         ptr = strchr(ptr, '>');
188                         if ((ptr == NULL) || (ptr >= msgend)) break;
189                         ++ptr;
190                         if ((ptr == NULL) || (ptr >= msgend)) break;
191                         msgstart = ptr;
192                 }
193
194                 /**
195                  * Any of these tags cause everything including and following
196                  * the tag to be removed.
197                  */
198                 if ( (!strncasecmp(ptr, "/HTML", 5))
199                    ||(!strncasecmp(ptr, "/BODY", 5)) ) {
200                         --ptr;
201                         msgend = ptr;
202                         strcpy(ptr, "");
203                         
204                 }
205
206                 ++ptr;
207         }
208         if (msgstart > msg) {
209                 strcpy(msg, msgstart);
210         }
211
212         /** Convert foreign character sets to UTF-8 if necessary. */
213 #ifdef HAVE_ICONV
214         if ( (strcasecmp(charset, "us-ascii"))
215            && (strcasecmp(charset, "UTF-8"))
216            && (strcasecmp(charset, ""))
217         ) {
218                 lprintf(9, "Converting %s to UTF-8\n", charset);
219                 ic = iconv_open("UTF-8", charset);
220                 if (ic == (iconv_t)(-1) ) {
221                         lprintf(5, "%s:%d iconv_open() failed: %s\n",
222                                 __FILE__, __LINE__, strerror(errno));
223                 }
224         }
225         if (ic != (iconv_t)(-1) ) {
226                 ibuf = msg;
227                 ibuflen = content_length;
228                 obuflen = content_length + (content_length / 2) ;
229                 obuf = (char *) malloc(obuflen);
230                 osav = obuf;
231                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
232                 content_length = content_length + (content_length / 2) - obuflen;
233                 osav[content_length] = 0;
234                 free(msg);
235                 msg = osav;
236                 iconv_close(ic);
237         }
238 #endif
239
240         /** FIXME At this point, shigerugo's messages are still clean.
241          *        Figure out what is mangling them below.
242          */
243
244         /** Now go through the message, parsing tags as necessary. */
245         converted_msg = malloc(content_length);
246         strcpy(converted_msg, "");
247         ptr = msgstart;
248         while (ptr < msgend) {
249                 /**
250                  * Change mailto: links to WebCit mail, by replacing the
251                  * link with one that points back to our mail room.  Due to
252                  * the way we parse URL's, it'll even handle mailto: links
253                  * that have "?subject=" in them.
254                  */
255                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
256                         content_length += 64;
257                         converted_msg = realloc(converted_msg, content_length);
258                         sprintf(&converted_msg[output_length],
259                                 "<a href=\"display_enter"
260                                 "?force_room=_MAIL_&recp=");
261                         output_length += 47;
262                         ptr = &ptr[16];
263                         ++alevel;
264                 }
265                 /** Make external links open in a separate window */
266                 else if (!strncasecmp(ptr, "<a href=", 8)) {
267                         ++alevel;
268                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
269                              &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
270                              ) {
271                                 /* open external links to new window */
272                                 content_length += 64;
273                                 converted_msg = realloc(converted_msg, content_length);
274                                 sprintf(&converted_msg[output_length], new_window);
275                                 output_length += strlen(new_window);
276                                 ptr = &ptr[8];
277                         }
278                         else if ( (treat_as_wiki) && (strncasecmp(ptr, "<a href=\"wiki?", 14)) ) {
279                                 lprintf(9, "converting wiki link\n");
280                                 content_length += 64;
281                                 converted_msg = realloc(converted_msg, content_length);
282                                 sprintf(&converted_msg[output_length], "<a href=\"wiki?page=");
283                                 output_length += 19;
284                                 ptr = &ptr[9];
285                         }
286                         else {
287                                 sprintf(&converted_msg[output_length], "<a href=");
288                                 output_length += 8;
289                                 ptr = &ptr[8];
290                         }
291                 }
292                 /**
293                  * Turn anything that looks like a URL into a real link, as long
294                  * as it's not inside a tag already
295                  */
296                 else if ( (brak == 0) && (alevel == 0)
297                      && (!strncasecmp(ptr, "http://", 7))) {
298                                 linklen = 0;
299                                 /** Find the end of the link */
300                                 for (i=0; i<=strlen(ptr); ++i) {
301                                         if ((ptr[i]==0)
302                                            ||(isspace(ptr[i]))
303                                            ||(ptr[i]==10)
304                                            ||(ptr[i]==13)
305                                            ||(ptr[i]=='(')
306                                            ||(ptr[i]==')')
307                                            ||(ptr[i]=='<')
308                                            ||(ptr[i]=='>')
309                                            ||(ptr[i]=='[')
310                                            ||(ptr[i]==']')
311                                         ) linklen = i;
312                                         if (linklen > 0) break;
313                                 }
314                                 if (linklen > 0) {
315                                         content_length += (32 + linklen);
316                                         converted_msg = realloc(converted_msg, content_length);
317                                         sprintf(&converted_msg[output_length], new_window);
318                                         output_length += strlen(new_window);
319                                         converted_msg[output_length] = '\"';
320                                         converted_msg[++output_length] = 0;
321                                         for (i=0; i<linklen; ++i) {
322                                                 converted_msg[output_length] = ptr[i];
323                                                 converted_msg[++output_length] = 0;
324                                         }
325                                         sprintf(&converted_msg[output_length], "\">");
326                                         output_length += 2;
327                                         for (i=0; i<linklen; ++i) {
328                                                 converted_msg[output_length] = *ptr++;
329                                                 converted_msg[++output_length] = 0;
330                                         }
331                                         sprintf(&converted_msg[output_length], "</A>");
332                                         output_length += 4;
333                                 }
334                 }
335                 else {
336                         /**
337                          * We need to know when we're inside a tag,
338                          * so we don't turn things that look like URL's into
339                          * links, when they're already links - or image sources.
340                          */
341                         if (*ptr == '<') ++brak;
342                         if (*ptr == '>') --brak;
343                         if (!strncasecmp(ptr, "</A>", 3)) --alevel;
344                         converted_msg[output_length] = *ptr++;
345                         converted_msg[++output_length] = 0;
346                 }
347         }
348
349         /** Output our big pile of markup */
350         client_write(converted_msg, output_length);
351
352         /** A little trailing vertical whitespace... */
353         wprintf("<br /><br />\n");
354
355         /** Now give back the memory */
356         free(converted_msg);
357         free(msg);
358 }
359
360 /*@}*/