Reorganized portions of html2html.c
[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         /**
241          *      At this point, the message has been stripped down to
242          *      only the content inside the <BODY></BODY> tags, and has
243          *      been converted to UTF-8 if it was originally in a foreign
244          *      character set.  The text is also guaranteed to be null
245          *      terminated now.
246          */
247
248         /** Now go through the message, parsing tags as necessary. */
249         converted_msg = malloc(content_length);
250         strcpy(converted_msg, "");
251         ptr = msg;
252         while (ptr < msgend) {
253                 /**
254                  * Change mailto: links to WebCit mail, by replacing the
255                  * link with one that points back to our mail room.  Due to
256                  * the way we parse URL's, it'll even handle mailto: links
257                  * that have "?subject=" in them.
258                  */
259                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
260                         content_length += 64;
261                         converted_msg = realloc(converted_msg, content_length);
262                         sprintf(&converted_msg[output_length],
263                                 "<a href=\"display_enter"
264                                 "?force_room=_MAIL_&recp=");
265                         output_length += 47;
266                         ptr = &ptr[16];
267                         ++alevel;
268                 }
269                 /** Make external links open in a separate window */
270                 else if (!strncasecmp(ptr, "<a href=", 8)) {
271                         ++alevel;
272                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
273                              &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
274                              ) {
275                                 /* open external links to new window */
276                                 content_length += 64;
277                                 converted_msg = realloc(converted_msg, content_length);
278                                 sprintf(&converted_msg[output_length], new_window);
279                                 output_length += strlen(new_window);
280                                 ptr = &ptr[8];
281                         }
282                         else if ( (treat_as_wiki) && (strncasecmp(ptr, "<a href=\"wiki?", 14)) ) {
283                                 lprintf(9, "converting wiki link\n");
284                                 content_length += 64;
285                                 converted_msg = realloc(converted_msg, content_length);
286                                 sprintf(&converted_msg[output_length], "<a href=\"wiki?page=");
287                                 output_length += 19;
288                                 ptr = &ptr[9];
289                         }
290                         else {
291                                 sprintf(&converted_msg[output_length], "<a href=");
292                                 output_length += 8;
293                                 ptr = &ptr[8];
294                         }
295                 }
296                 /**
297                  * Turn anything that looks like a URL into a real link, as long
298                  * as it's not inside a tag already
299                  */
300                 else if ( (brak == 0) && (alevel == 0)
301                      && (!strncasecmp(ptr, "http://", 7))) {
302                                 linklen = 0;
303                                 /** Find the end of the link */
304                                 for (i=0; i<=strlen(ptr); ++i) {
305                                         if ((ptr[i]==0)
306                                            ||(isspace(ptr[i]))
307                                            ||(ptr[i]==10)
308                                            ||(ptr[i]==13)
309                                            ||(ptr[i]=='(')
310                                            ||(ptr[i]==')')
311                                            ||(ptr[i]=='<')
312                                            ||(ptr[i]=='>')
313                                            ||(ptr[i]=='[')
314                                            ||(ptr[i]==']')
315                                         ) linklen = i;
316                                         if (linklen > 0) break;
317                                 }
318                                 if (linklen > 0) {
319                                         content_length += (32 + linklen);
320                                         converted_msg = realloc(converted_msg, content_length);
321                                         sprintf(&converted_msg[output_length], new_window);
322                                         output_length += strlen(new_window);
323                                         converted_msg[output_length] = '\"';
324                                         converted_msg[++output_length] = 0;
325                                         for (i=0; i<linklen; ++i) {
326                                                 converted_msg[output_length] = ptr[i];
327                                                 converted_msg[++output_length] = 0;
328                                         }
329                                         sprintf(&converted_msg[output_length], "\">");
330                                         output_length += 2;
331                                         for (i=0; i<linklen; ++i) {
332                                                 converted_msg[output_length] = *ptr++;
333                                                 converted_msg[++output_length] = 0;
334                                         }
335                                         sprintf(&converted_msg[output_length], "</A>");
336                                         output_length += 4;
337                                 }
338                 }
339                 else {
340                         /**
341                          * We need to know when we're inside a tag,
342                          * so we don't turn things that look like URL's into
343                          * links, when they're already links - or image sources.
344                          */
345                         if (*ptr == '<') ++brak;
346                         if (*ptr == '>') --brak;
347                         if (!strncasecmp(ptr, "</A>", 3)) --alevel;
348                         converted_msg[output_length] = *ptr++;
349                         converted_msg[++output_length] = 0;
350                 }
351         }
352
353         /**     uncomment these two lines to override conversion        */
354         /**     memcpy(converted_msg, msg, content_length);             */
355         /**     output_length = content_length;                         */
356
357         /** Output our big pile of markup */
358         client_write(converted_msg, output_length);
359
360         /** A little trailing vertical whitespace... */
361         wprintf("<br /><br />\n");
362
363         /** Now give back the memory */
364         free(converted_msg);
365         free(msg);
366 }
367
368 /*@}*/