* Applied matt's patch to have it show a loading graphic for ajax operations
[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         size_t converted_alloc = 0;
81         int buffer_length = 1;
82         int line_length = 0;
83         int content_length = 0;
84         int output_length = 0;
85         char new_window[SIZ];
86         int brak = 0;
87         int alevel = 0;
88         int i;
89         int linklen;
90         char charset[128];
91 #ifdef HAVE_ICONV
92         iconv_t ic = (iconv_t)(-1) ;
93         char *ibuf;                   /**< Buffer of characters to be converted */
94         char *obuf;                   /**< Buffer for converted characters      */
95         size_t ibuflen;               /**< Length of input buffer               */
96         size_t obuflen;               /**< Length of output buffer              */
97         char *osav;                   /**< Saved pointer to output buffer       */
98 #endif
99
100         safestrncpy(charset, supplied_charset, sizeof charset);
101         msg = strdup("");
102         sprintf(new_window, "<a target=\"%s\" href=", TARGET);
103
104         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
105                 line_length = strlen(buf);
106                 buffer_length = content_length + line_length + 2;
107                 ptr = realloc(msg, buffer_length);
108                 if (ptr == NULL) {
109                         wprintf("<b>");
110                         wprintf(_("realloc() error! couldn't get %d bytes: %s"),
111                                 buffer_length + 1,
112                                 strerror(errno));
113                         wprintf("</b><br /><br />\n");
114                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
115                                 /** flush */
116                         }
117                         free(msg);
118                         return;
119                 }
120                 msg = ptr;
121                 strcpy(&msg[content_length], buf);
122                 content_length += line_length;
123                 strcpy(&msg[content_length], "\n");
124                 content_length += 1;
125         }
126
127         /** Do a first pass to isolate the message body */
128         ptr = msg;
129         msgstart = msg;
130         msgend = &msg[content_length];
131
132         while (ptr < msgend) {
133
134                 /** Advance to next tag */
135                 ptr = strchr(ptr, '<');
136                 if ((ptr == NULL) || (ptr >= msgend)) break;
137                 ++ptr;
138                 if ((ptr == NULL) || (ptr >= msgend)) break;
139
140                 /**
141                  *  Look for META tags.  Some messages (particularly in
142                  *  Asian locales) illegally declare a message's character
143                  *  set in the HTML instead of in the MIME headers.  This
144                  *  is wrong but we have to work around it anyway.
145                  */
146                 if (!strncasecmp(ptr, "META", 4)) {
147
148                         char *meta_start;
149                         char *meta_end;
150                         int meta_length;
151                         char *meta;
152                         char *meta_http_equiv;
153                         char *meta_content;
154                         char *spaceptr;
155
156                         meta_start = &ptr[4];
157                         meta_end = strchr(ptr, '>');
158                         if ((meta_end != NULL) && (meta_end <= msgend)) {
159                                 meta_length = meta_end - meta_start + 1;
160                                 meta = malloc(meta_length + 1);
161                                 safestrncpy(meta, meta_start, meta_length);
162                                 meta[meta_length] = 0;
163                                 striplt(meta);
164                                 if (!strncasecmp(meta, "HTTP-EQUIV=", 11)) {
165                                         meta_http_equiv = strdup(&meta[11]);
166                                         spaceptr = strchr(meta_http_equiv, ' ');
167                                         if (spaceptr != NULL) {
168                                                 *spaceptr = 0;
169                                                 meta_content = strdup(++spaceptr);
170                                                 if (!strncasecmp(meta_content, "content=", 8)) {
171                                                         strcpy(meta_content, &meta_content[8]);
172                                                         stripquotes(meta_http_equiv);
173                                                         stripquotes(meta_content);
174                                                         extract_charset_from_meta(charset,
175                                                                 meta_http_equiv, meta_content);
176                                                 }
177                                                 free(meta_content);
178                                         }
179                                         free(meta_http_equiv);
180                                 }
181                                 free(meta);
182                         }
183                 }
184
185                 /**
186                  * Any of these tags cause everything up to and including
187                  * the tag to be removed.
188                  */     
189                 if ( (!strncasecmp(ptr, "HTML", 4))
190                    ||(!strncasecmp(ptr, "HEAD", 4))
191                    ||(!strncasecmp(ptr, "/HEAD", 5))
192                    ||(!strncasecmp(ptr, "BODY", 4)) ) {
193                         ptr = strchr(ptr, '>');
194                         if ((ptr == NULL) || (ptr >= msgend)) break;
195                         ++ptr;
196                         if ((ptr == NULL) || (ptr >= msgend)) break;
197                         msgstart = ptr;
198                 }
199
200                 /**
201                  * Any of these tags cause everything including and following
202                  * the tag to be removed.
203                  */
204                 if ( (!strncasecmp(ptr, "/HTML", 5))
205                    ||(!strncasecmp(ptr, "/BODY", 5)) ) {
206                         --ptr;
207                         msgend = ptr;
208                         strcpy(ptr, "");
209                         
210                 }
211
212                 ++ptr;
213         }
214         if (msgstart > msg) {
215                 strcpy(msg, msgstart);
216         }
217
218         /** Convert foreign character sets to UTF-8 if necessary. */
219 #ifdef HAVE_ICONV
220         if ( (strcasecmp(charset, "us-ascii"))
221            && (strcasecmp(charset, "UTF-8"))
222            && (strcasecmp(charset, ""))
223         ) {
224                 lprintf(9, "Converting %s to UTF-8\n", charset);
225                 ic = ctdl_iconv_open("UTF-8", charset);
226                 if (ic == (iconv_t)(-1) ) {
227                         lprintf(5, "%s:%d iconv_open() failed: %s\n",
228                                 __FILE__, __LINE__, strerror(errno));
229                 }
230         }
231         if (ic != (iconv_t)(-1) ) {
232                 ibuf = msg;
233                 ibuflen = content_length;
234                 obuflen = content_length + (content_length / 2) ;
235                 obuf = (char *) malloc(obuflen);
236                 osav = obuf;
237                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
238                 content_length = content_length + (content_length / 2) - obuflen;
239                 osav[content_length] = 0;
240                 free(msg);
241                 msg = osav;
242                 iconv_close(ic);
243         }
244 #endif
245
246         /**
247          *      At this point, the message has been stripped down to
248          *      only the content inside the <BODY></BODY> tags, and has
249          *      been converted to UTF-8 if it was originally in a foreign
250          *      character set.  The text is also guaranteed to be null
251          *      terminated now.
252          */
253
254         /** Now go through the message, parsing tags as necessary. */
255         converted_alloc = content_length + 8192;
256         converted_msg = malloc(converted_alloc);
257         if (converted_msg == NULL) {
258                 abort();                        /* FIXME */
259         }
260         strcpy(converted_msg, "");
261         ptr = msg;
262         msgend = strchr(msg, 0);
263         while (ptr < msgend) {
264
265                 /**
266                  * Change mailto: links to WebCit mail, by replacing the
267                  * link with one that points back to our mail room.  Due to
268                  * the way we parse URL's, it'll even handle mailto: links
269                  * that have "?subject=" in them.
270                  */
271                 if (!strncasecmp(ptr, "<a href=\"mailto:", 16)) {
272                         content_length += 64;
273                         if (content_length >= converted_alloc) {
274                                 converted_alloc += 8192;
275                                 converted_msg = realloc(converted_msg, converted_alloc);
276                                 if (converted_msg == NULL) {
277                                         abort();
278                                 }
279                         }
280                         sprintf(&converted_msg[output_length],
281                                 "<a href=\"display_enter"
282                                 "?force_room=_MAIL_&recp=");
283                         output_length += 47;
284                         ptr = &ptr[16];
285                         ++alevel;
286                 }
287                 /** Make external links open in a separate window */
288                 else if (!strncasecmp(ptr, "<a href=\"", 9)) {
289                         ++alevel;
290                         if ( ((strchr(ptr, ':') < strchr(ptr, '/')))
291                              &&  ((strchr(ptr, '/') < strchr(ptr, '>'))) 
292                              ) {
293                                 /* open external links to new window */
294                                 content_length += 64;
295                                 if (content_length >= converted_alloc) {
296                                         converted_alloc += 8192;
297                                         converted_msg = realloc(converted_msg, converted_alloc);
298                                         if (converted_msg == NULL) {
299                                                 abort();
300                                         }
301                                 }
302                                 sprintf(&converted_msg[output_length], new_window);
303                                 output_length += strlen(new_window);
304                                 ptr = &ptr[8];
305                         }
306                         else if ( (treat_as_wiki) && (strncasecmp(ptr, "<a href=\"wiki?", 14)) ) {
307                                 content_length += 64;
308                                 if (content_length >= converted_alloc) {
309                                         converted_alloc += 8192;
310                                         converted_msg = realloc(converted_msg, converted_alloc);
311                                         if (converted_msg == NULL) {
312                                                 abort();
313                                         }
314                                 }
315                                 sprintf(&converted_msg[output_length], "<a href=\"wiki?page=");
316                                 output_length += 19;
317                                 ptr = &ptr[9];
318                         }
319                         else {
320                                 sprintf(&converted_msg[output_length], "<a href=\"");
321                                 output_length += 9;
322                                 ptr = &ptr[9];
323                         }
324                 }
325                 /**
326                  * Turn anything that looks like a URL into a real link, as long
327                  * as it's not inside a tag already
328                  */
329                 else if ( (brak == 0) && (alevel == 0)
330                      && (!strncasecmp(ptr, "http://", 7))) {
331                                 linklen = 0;
332                                 /** Find the end of the link */
333                                 for (i=0; i<=strlen(ptr); ++i) {
334                                         if ((ptr[i]==0)
335                                            ||(isspace(ptr[i]))
336                                            ||(ptr[i]==10)
337                                            ||(ptr[i]==13)
338                                            ||(ptr[i]=='(')
339                                            ||(ptr[i]==')')
340                                            ||(ptr[i]=='<')
341                                            ||(ptr[i]=='>')
342                                            ||(ptr[i]=='[')
343                                            ||(ptr[i]==']')
344                                         ) linklen = i;
345                                         if (linklen > 0) break;
346                                 }
347                                 if (linklen > 0) {
348                                         content_length += (32 + linklen);
349                                         if (content_length >= converted_alloc) {
350                                                 converted_alloc += 8192;
351                                                 converted_msg = realloc(converted_msg, converted_alloc);
352                                                 if (converted_msg == NULL) {
353                                                         abort();
354                                                 }
355                                         }
356                                         sprintf(&converted_msg[output_length], new_window);
357                                         output_length += strlen(new_window);
358                                         converted_msg[output_length] = '\"';
359                                         converted_msg[++output_length] = 0;
360                                         for (i=0; i<linklen; ++i) {
361                                                 converted_msg[output_length] = ptr[i];
362                                                 converted_msg[++output_length] = 0;
363                                         }
364                                         sprintf(&converted_msg[output_length], "\">");
365                                         output_length += 2;
366                                         for (i=0; i<linklen; ++i) {
367                                                 converted_msg[output_length] = *ptr++;
368                                                 converted_msg[++output_length] = 0;
369                                         }
370                                         sprintf(&converted_msg[output_length], "</A>");
371                                         output_length += 4;
372                                 }
373                 }
374                 else {
375                         /**
376                          * We need to know when we're inside a tag,
377                          * so we don't turn things that look like URL's into
378                          * links, when they're already links - or image sources.
379                          */
380                         if (*ptr == '<') ++brak;
381                         if (*ptr == '>') --brak;
382                         if (!strncasecmp(ptr, "</A>", 3)) --alevel;
383                         converted_msg[output_length] = *ptr++;
384                         converted_msg[++output_length] = 0;
385                 }
386         }
387
388         /**     uncomment these two lines to override conversion        */
389         /**     memcpy(converted_msg, msg, content_length);             */
390         /**     output_length = content_length;                         */
391
392         /** Output our big pile of markup */
393         client_write(converted_msg, output_length);
394
395         /** A little trailing vertical whitespace... */
396         wprintf("<br /><br />\n");
397
398         /** Now give back the memory */
399         if (converted_msg != NULL) free(converted_msg);
400         if (msg != NULL) free(msg);
401 }
402
403 /*@}*/