BIG, experimental patch.
[cocanwiki.git] / scripts / wikilib.ml
1 (* COCANWIKI - a wiki written in Objective CAML.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: wikilib.ml,v 1.12 2004/10/11 14:13:04 rich Exp $
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; see the file COPYING.  If not, write to
18  * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *)
21
22 open Apache
23 open Registry
24 open Cgi
25 open Cgi_escape
26 open Printf
27
28 open ExtString
29
30 open Cocanwiki_strings
31
32 (* Generate a URL for a new page with the given title.  This code checks
33  * if the URL already exists in the database and can return one of several
34  * errors.
35  *)
36 type genurl_error_t = GenURL_OK of string
37                     | GenURL_TooShort
38                     | GenURL_BadURL
39                     | GenURL_Duplicate of string
40
41 let nontrivial_re = Pcre.regexp ~flags:[`CASELESS] "[a-z0-9]"
42
43 let generate_url_of_title (dbh : Dbi.connection) hostid title =
44   (* Create a suitable URL from this title. *)
45   let url =
46     String.map (function
47                     '\000' .. ' ' | '<' | '>' | '&' | '"' | '+' | '#' | '%'
48                       -> '_'
49                   | c -> Char.lowercase c) title in
50
51   (* Check URL is not too trivial. *)
52   if not (Pcre.pmatch ~rex:nontrivial_re url) then
53     GenURL_TooShort
54   (* URL cannot begin with '_'. *)
55   else if url.[0] = '_' then
56     GenURL_BadURL
57   else (
58     (* Check that the URL doesn't already exist in the database.  If it does
59      * then it probably means that another page exists with similar enough
60      * content, so we should redirect to there instead.
61      *)
62     let sth = dbh#prepare_cached "select 1 from pages
63                                    where hostid = ? and url = ?" in
64     sth#execute [`Int hostid; `String url];
65
66     try
67       sth#fetch1int ();
68       GenURL_Duplicate url
69     with
70         Not_found ->
71           GenURL_OK url
72   )
73
74 (* Obscure a mailto: URL against spammers. *)
75 let obscure_mailto url =
76   if String.length url > 8 then (
77     let c7 = Char.code url.[7] in
78     let c8 = Char.code url.[8] in
79     let start = String.sub url 0 7 in
80     let rest = escape_html_tag (String.sub url 9 (String.length url - 9)) in
81     sprintf "%s&#x%02x;&#x%02x;%s" start c7 c8 rest
82   )
83   else
84     url
85
86 (* Convert Wiki markup to XHTML 1.0.
87  *
88  * Shortcomings:
89  * Doesn't support multi-level bullet points. (XXX)
90  * Intra-page links. (XXX)
91  *)
92
93 (* This matches any markup. *)
94 let markup_re =
95   let link = "\\[\\[\\s*(?:.+?)\\s*(?:\\|.+?\\s*)?\\]\\]" in
96   let tag = "</?(?:b|i|strong|em|code|tt|sup|sub|nowiki|big|small|strike|s|br)>" in
97   Pcre.regexp ("(.*?)((?:" ^ link ^ ")|(?:" ^ tag ^ "))(.*)")
98
99 (* This matches links only, and should be compatible with the link contained
100  * in the above regexp.
101  *)
102 let link_re = Pcre.regexp "\\[\\[\\s*(.+?)\\s*(?:\\|(.+?)\\s*)?\\]\\]"
103
104 let image_re =
105   Pcre.regexp "^(image|thumb(?:nail)?):\\s*([a-z0-9][_a-z0-9]*\\.(?:jpg|jpeg|gif|ico|png))$"
106 let file_re =
107   Pcre.regexp "^file:\\s*([a-z0-9][-._a-z0-9]*)$"
108
109 let url_re = Pcre.regexp "^[a-z]+://"
110 let mailto_re = Pcre.regexp "^mailto:"
111
112 (* Links. *)
113 let markup_link dbh hostid link =
114   let subs = Pcre.exec ~rex:link_re link in
115   let url = Pcre.get_substring subs 1 in
116
117   let tag name = function
118       `Null -> ""
119     | `String v -> " " ^ name ^ "=\"" ^ escape_html_tag v ^ "\""
120   in
121
122   if Pcre.pmatch ~rex:image_re url then (
123     (* It may be an image. *)
124     let subs = Pcre.exec ~rex:image_re url in
125     let is_thumb = (Pcre.get_substring subs 1).[0] = 't' in
126     let name = Pcre.get_substring subs 2 in
127
128     let sql = "select id, " ^
129               (if is_thumb then "tn_width, tn_height"
130                else "width, height") ^
131               ", alt, title, longdesc, class
132                from images
133               where hostid = ? and name = ?" in
134     let sth = dbh#prepare_cached sql in
135     sth#execute [`Int hostid; `String name];
136
137     try
138       let imageid, width, height, alt, title, longdesc, clasz =
139         match sth#fetch1 () with
140             [`Int imageid; `Int width; `Int height; `String alt;
141              (`Null | `String _) as title;
142              (`Null | `String _) as longdesc;
143              (`Null | `String _) as clasz] ->
144               imageid, width, height, alt, title, longdesc, clasz
145           | _ -> assert false in
146
147       let link = "/_image/" ^ escape_url name in
148
149       (if is_thumb then "<a href=\"" ^ link ^ "\">" else "") ^
150       "<img src=\"" ^ link ^ "?version=" ^ string_of_int imageid ^
151       (if is_thumb then "&thumbnail=1" else "") ^
152       "\" width=\"" ^
153       string_of_int width ^
154       "\" height=\"" ^
155       string_of_int height ^
156       "\" alt=\"" ^
157       escape_html_tag alt ^
158       "\"" ^
159       tag "title" title ^
160       tag "longdesc" longdesc ^
161       tag "class" clasz ^
162       "/>" ^
163       (if is_thumb then "</a>" else "")
164     with
165         Not_found ->
166           (* Image not found. *)
167           "<a class=\"image_not_found\" " ^
168           "href=\"/_bin/upload_image_form.cmo?name=" ^
169           escape_url name ^
170           "\">" ^
171           escape_html name ^
172           "</a>"
173   ) else if Pcre.pmatch ~rex:file_re url then (
174     (* It may be a file. *)
175     let subs = Pcre.exec ~rex:file_re url in
176     let name = Pcre.get_substring subs 1 in
177
178     let sth = dbh#prepare_cached "select title
179                                     from files
180                                    where hostid = ? and name = ?" in
181     sth#execute [`Int hostid; `String name];
182
183     try
184       let title =
185         match sth#fetch1 () with
186             [(`Null | `String _) as title] -> title
187           | _ -> assert false in
188
189       "<a href=\"/_file/" ^
190       escape_url name ^
191       "\"" ^
192       tag "title" title ^
193       ">" ^
194       escape_html name ^
195       "</a>"
196     with
197         Not_found ->
198           (* File not found. *)
199           "<a class=\"file_not_found\" " ^
200           "href=\"/_bin/upload_file_form.cmo?name=" ^
201           escape_url name ^
202           "\">" ^
203           escape_html name ^
204           "</a>"
205   ) else (
206     (* Pcre changed behaviour between versions.  Previously a non-capture
207      * would return "".  Now it throws 'Not_found'.
208      *)
209     let text =
210       try Pcre.get_substring subs 2
211       with Not_found -> "" in
212     let text = if text = "" then url else text in
213
214     (* XXX Escaping here is very hairy indeed.  (See also the obscure_mailto
215      * function which performs some escaping ...)
216      *)
217
218     let url, clasz, title =
219       if Pcre.pmatch ~rex:url_re url then
220         escape_html_tag url, "external", url (* http://.... *)
221       else if Pcre.pmatch ~rex:mailto_re url then (
222         obscure_mailto url, "mailto", url
223       ) else (
224         let title = url in
225         (* Look up the 'URL' against the titles in the database and
226          * obtain the real URL.
227          *)
228         let sth = dbh#prepare_cached "select url from pages
229                                        where hostid = ? and url is not null
230                                          and lower (title) = lower (?)" in
231         sth#execute [`Int hostid; `String url];
232
233         try
234           let url = sth#fetch1string () in
235           "/" ^ url, "internal", title
236         with
237             Not_found ->
238               (* It might be a template page ...  These pages don't
239                * exist in the template, but can be synthesized on the
240                * fly by page.ml.
241                *)
242               let is_template_page url =
243                 let sth = dbh#prepare_cached "select 1 from templates
244                                                where ? ~ url_regexp
245                                                order by ordering
246                                                limit 1" in
247                 sth#execute [`String url];
248
249                 try sth#fetch1int () = 1 with Not_found -> false
250               in
251
252               if is_template_page url then
253                 "/" ^ url, "internal", title
254               else
255                 (* No, it really doesn't exist, so make it a link to
256                  * a new page.
257                  *)
258               "/_bin/edit.cmo?title=" ^ escape_url url, "newpage", title
259       ) in
260
261     "<a href=\"" ^ url ^
262     "\" class=\"" ^ clasz ^
263     "\" title=\"" ^ escape_html_tag title ^ "\">" ^
264     escape_html text ^ "</a>"
265   )
266
267 type find_t = FoundNothing
268             | FoundOpen of string * string * string
269             | FoundClose of string * string * string * string
270             | FoundLink of string * string * string
271
272 let _markup_paragraph dbh hostid text =
273   let find_earliest_markup text =
274     let convert_b_and_i elem =
275       if elem = "b" then "strong"
276       else if elem = "i" then "em"
277       else elem
278     in
279
280     try
281       let subs = Pcre.exec ~rex:markup_re text in
282       let first = Pcre.get_substring subs 1 in
283       let markup = Pcre.get_substring subs 2 in
284       let rest = Pcre.get_substring subs 3 in
285       if String.length markup > 2 &&
286         markup.[0] = '[' && markup.[1] = '[' then (
287           let link = markup_link dbh hostid markup in
288           FoundLink (first, link, rest)
289         )
290       else if String.length markup > 2 &&
291         markup.[0] = '<' && markup.[1] = '/' then (
292           let elem = String.sub markup 2 (String.length markup - 3) in
293           let elem = convert_b_and_i elem in
294           FoundClose (first, elem, rest, markup ^ rest)
295         )
296       else if String.length markup > 1 && markup.[0] = '<' then (
297         let elem = String.sub markup 1 (String.length markup - 2) in
298         let elem = convert_b_and_i elem in
299         FoundOpen (first, elem, rest)
300       )
301       else
302         failwith ("bad regexp: markup is '" ^ markup ^ "'");
303     with
304         Not_found -> FoundNothing
305   in
306
307   (* This code performs markup for a "paragraph" unit.  The strategy
308    * is to look for the next matching markup or link, process that, and
309    * then continue recursively with the remainder of the string.  We also
310    * maintain a stack which is our current level of nesting of <b>-like
311    * operators.
312    *)
313   let rec loop = function
314     | "", [] -> [""]                    (* base case *)
315
316     | text, ("nowiki" :: stack) ->
317         (*prerr_endline ("nowiki case: text = " ^ text);*)
318
319         (* If the top of the stack is <nowiki> then we're just looking for
320          * the closing </nowiki>, and nothing else matters. *)
321         (match Pcre.split ~pat:"</nowiki>" ~max:2 text with
322            | [] -> loop ("", stack)
323            | [x] -> escape_html x :: loop ("", stack)
324            | [x;y] -> escape_html x :: loop (y, stack)
325            | _ -> assert false)
326
327     | "", (x :: xs) ->                  (* base case, popping the stack *)
328         "</" :: x :: ">" :: loop ("", xs)
329
330     | text, [] ->
331         (*prerr_endline ("text = " ^ text ^ ", stack empty");*)
332
333         (* Look for the earliest possible matching markup.  Because the
334          * stack is empty, we're not looking for closing tags.
335          *)
336         (match find_earliest_markup text with
337            | FoundNothing -> escape_html text :: []
338            | FoundClose (first, elem, rest, _) ->
339                (* close tags ignored *)
340                escape_html first :: "&lt;/" :: escape_html elem :: "&gt;" ::
341                  loop (rest, [])
342            | FoundOpen (first, elem, rest) when elem = "nowiki" ->
343                (* handle <nowiki> specially ... *)
344                escape_html first :: loop (rest, elem :: [])
345            | FoundOpen (first, elem, rest) when elem = "br" ->
346                (* handle <br> specially ... *)
347                escape_html first :: "<br/>" :: loop (rest, [])
348            | FoundOpen (first, elem, rest) ->
349                (* open tag - push it onto the stack *)
350                escape_html first :: "<" :: elem :: ">" :: loop (rest, [elem])
351            | FoundLink (first, link, rest) ->
352                escape_html first :: link :: loop (rest, [])
353         )
354
355     | text, ((x :: xs) as stack) ->
356         (*prerr_endline ("text = " ^ text ^ ", top of stack = " ^ x ^
357           ", stack size = " ^ string_of_int (List.length stack));*)
358
359         (* Look for the earliest possible matching markup. *)
360         (match find_earliest_markup text with
361            | FoundNothing -> escape_html text :: loop ("", stack)
362            | FoundClose (first, elem, rest, _) when x = elem ->
363                (* matching close tag *)
364                escape_html first :: "</" :: elem :: ">" :: loop (rest, xs)
365            | FoundClose (first, elem, rest, elem_rest) ->
366                (* non-matching close tag *)
367                escape_html first :: "</" :: x :: ">" :: loop (elem_rest, xs)
368            | FoundOpen (first, elem, rest) when elem = "nowiki" ->
369                (* handle <nowiki> specially ... *)
370                escape_html first :: loop (rest, elem :: stack)
371            | FoundOpen (first, elem, rest) when elem = "br" ->
372                (* handle <br> specially ... *)
373                escape_html first :: "<br/>" :: loop (rest, stack)
374            | FoundOpen (first, elem, rest) ->
375                (* open tag - push it onto the stack *)
376                escape_html first :: "<" :: elem :: ">" ::
377                  loop (rest, elem :: stack)
378            | FoundLink (first, link, rest) ->
379                (* link *)
380                escape_html first :: link :: loop (rest, stack)
381         )
382   in
383
384   (*prerr_endline ("original markup = " ^ text);*)
385   let text = loop (text, []) in
386   let text = String.concat "" text in
387   (*prerr_endline ("after loop = " ^ text);*)
388   text
389
390 let markup_paragraph dbh hostid text =
391   "<p>" ^ _markup_paragraph dbh hostid text ^ "</p>"
392
393 let markup_heading dbh hostid level text =
394   let text = _markup_paragraph dbh hostid text in
395   sprintf "<h%d>%s</h%d>" level text level
396
397 let markup_ul dbh hostid lines =
398   "<ul><li>" ^
399   String.concat "</li>\n<li>"
400     (List.map (fun t -> _markup_paragraph dbh hostid t) lines) ^
401   "</li></ul>"
402
403 let markup_ol dbh hostid lines =
404   "<ol><li>" ^
405   String.concat "</li>\n<li>"
406     (List.map (fun t -> _markup_paragraph dbh hostid t) lines) ^
407   "</li></ol>"
408
409 let markup_pre lines =
410   "<pre>\n" ^
411   String.concat "\n" (List.map Cgi_escape.escape_html lines) ^
412   "\n</pre>\n"
413
414 (* Validate HTML permitted in between <html> ... </html> markers.
415  * Note that what we support is a very limited but strict subset of XHTML
416  * 1.0.  Actually, that's not true.  We should really use an XML parser
417  * and a proper DTD here to ensure elements only appear in the correct
418  * context ...
419  *)
420 let split_tags_re = Pcre.regexp ~flags:[`DOTALL] "<.*?>|[^<]+"
421
422 let open_attr_re = Pcre.regexp "^<([a-z]+)\\s*([^>]*?)(/?)>$"
423 let close_attr_re = Pcre.regexp "^</([a-z]+)>$"
424
425 let allowed_elements =
426   let basic = [
427     "p", [];
428     "ul", []; "ol", []; "li", [];
429     "pre", []; "blockquote", ["cite"];
430     "strong", []; "em", []; "dfn", []; "code", []; "tt", [];
431     "samp", []; "kbd", []; "var", []; "cite", [];
432     "sup", []; "sub", []; "q", [];
433     "abbr", []; "acronym", [];
434     "b", []; "i", [];
435     "big", []; "small", []; "strike", []; "s", [];
436     "div", []; "span", [];
437     "br", [];
438   ] in
439   let headers = [ "h3", []; "h4", []; "h5", []; "h6", [] ] in
440   let links = [ "a", ["href"] ] in
441   let images = [ "img", ["src"; "alt"; "width"; "height"; "longdesc"] ] in
442
443   let forms = [
444     "form", [ "method"; "action"; "enctype" ];
445     "input", [ "name"; "value"; "type"; "size"; "maxlength" ];
446     "textarea", [ "name"; "rows"; "cols" ];
447   ] in
448
449   let tables = [
450     "table", []; "tr", [];
451     "th", [ "colspan"; "rowspan" ]; "td", [ "colspan"; "rowspan" ];
452     "thead", []; "tbody", []
453   ] in
454
455   basic @ headers @ links @ images @ forms @ tables
456
457 let standard_tags = [ "title"; "lang"; "class"; "id" ]
458
459 (* Parse a list of tags like:
460  * name="value" name="value with space"
461  * into an assoc list.  The tricky bit is that there may be
462  * spaces within the quoted strings.
463  *)
464 let parse_tags str =
465   if str = "" then []                   (* Very common case. *)
466   else (
467     let len = String.length str in
468
469     let fail () = invalid_arg ("bad tags near: " ^ truncate 20 str) in
470     let get_alphas i =
471       let b = Buffer.create 100 in
472       let rec loop i =
473         if i < len && isalpha str.[i] then (
474           Buffer.add_char b str.[i];
475           loop (i+1)
476         ) else
477           Buffer.contents b, i
478       in
479       loop i
480     in
481     let get_to_next_quote i =
482       let b = Buffer.create 100 in
483       let rec loop i =
484         if i < len && str.[i] <> '"' then (
485           Buffer.add_char b str.[i];
486           loop (i+1)
487         ) else
488           Buffer.contents b, (i+1)
489       in
490       loop i
491     in
492
493     let r = ref [] in
494     let rec loop i =
495       if i >= len then !r
496       else (
497         let c = str.[i] in
498         if isspace c then loop (i+1)
499         else if isalpha c then (
500           let name, i = get_alphas i in
501           if String.length str > i && str.[i] = '=' && str.[i+1] = '"' then (
502             let value, i = get_to_next_quote (i+2) in
503             r := (name, value) :: !r;
504             loop i
505           )
506           else fail ()
507         )
508         else fail ()
509       )
510     in
511     loop 0
512   )
513
514 type valid_t = VText of string
515              | VOpen of string * (string * string) list
516              | VClose of string
517
518 let validate html =
519   (* Split into attrs and non-attrs.  We end up with a list like this:
520    * [ "<ul>"; "<li>"; "Some text"; "</li>"; ... ]
521    *)
522   let html =
523     try
524       let html = Pcre.extract_all ~rex:split_tags_re html in
525       let html = Array.to_list html in
526       List.map (function [| a |] -> a | _ -> assert false) html
527     with
528         Not_found -> [] in
529
530   (* Parse up each attribute to get the tags. *)
531   let html =
532     List.concat
533       (List.map
534          (fun str ->
535             if String.length str >= 2 && str.[0] = '<' then (
536               try
537                 if str.[1] <> '/' then (
538                   (* Possible open attr. *)
539                   let subs = Pcre.exec ~rex:open_attr_re str in
540                   let attr = Pcre.get_substring subs 1 in
541                   let tags = Pcre.get_substring subs 2 in
542                   let close = Pcre.get_substring subs 3 = "/" in
543                   let tags = parse_tags tags in
544                   if not close then
545                     [VOpen (attr, tags)]
546                   else
547                     [VOpen (attr, tags); VClose attr]
548                 ) else (
549                   (* Possible close attr. *)
550                   let subs = Pcre.exec ~rex:close_attr_re str in
551                   let attr = Pcre.get_substring subs 1 in
552                   [VClose attr]
553                 )
554               with
555                   Not_found ->
556                     invalid_arg ("invalid element near " ^ truncate 20 str)
557             ) else (
558               (* Ordinary text.  Check no < or > characters. *)
559               (* XXX Check for valid &quoted; entities. *)
560               if String.contains str '<' || String.contains str '>' then
561                 invalid_arg
562                   ("unquoted '<' or '>' characters near " ^ truncate 20 str);
563               [VText str]
564             )
565          ) html
566       ) in
567
568   (* Check that opening/closing tags match. *)
569   let rec loop stack html =
570     match stack, html with
571       | [], [] -> ()
572       | (attr :: _), [] ->
573           invalid_arg ("mismatched element: " ^ truncate 20 attr)
574       | stack, (VOpen (attr, _) :: xs) ->
575           loop (attr :: stack) xs
576       | (attr1 :: stack), (VClose attr2 :: xs) when attr1 = attr2 ->
577           loop stack xs
578       | (attr1 :: stack), (VClose attr2 :: xs) ->
579           invalid_arg ("open/close elements don't match: " ^
580                        truncate 20 attr1 ^ " and: " ^
581                        truncate 20 attr2)
582       | [], (VClose attr2 :: _) ->
583           invalid_arg ("close element with no matching open: " ^
584                        truncate 20 attr2)
585       | stack, (VText _ :: xs) ->
586           loop stack xs
587   in
588   loop [] html;
589
590   (* Now check that we only use the permitted elements. *)
591   let rec loop = function
592     | [] -> ()
593     | (VOpen (attr, tags)) :: xs ->
594         (try
595            let allowed_tags = List.assoc attr allowed_elements in
596            let allowed_tags = allowed_tags @ standard_tags in
597            List.iter (fun (tag, _) ->
598                         if not (List.mem tag allowed_tags) then
599                           raise Not_found) tags;
600            loop xs
601          with
602              Not_found ->
603                invalid_arg ("this HTML attr is not allowed or contains a " ^
604                             "tag which is not permitted: " ^
605                             truncate 20 attr))
606     | _ :: xs -> loop xs
607   in
608   loop html
609
610 type preline_t = STpHTML of string list (* Block of HTML. *)
611                | STpLine of string      (* A line. *)
612
613 type line_t = STBlank
614             | STHeading of int * string (* <h3>, <h4>, ... *)
615             | STUnnumbered of string list (* <ul> *)
616             | STNumbered of string list (* <ol> *)
617             | STPreformatted of string list (* <pre> *)
618             | STParagraph of string     (* Ordinary <p> *)
619             | STHTML of string list     (* Block of (unvalidated) HTML. *)
620
621 let split_lines_re = Pcre.regexp "\\r?\\n"
622 let blank_re = Pcre.regexp "^\\s*$"
623 let heading_re = Pcre.regexp "^(=+)\\s+(.*)"
624 let unnumbered_re = Pcre.regexp "^(\\*)\\s+(.*)"
625 let numbered_re = Pcre.regexp "^(\\#)\\s+(.*)"
626 let preformatted_re = Pcre.regexp "^ (.*)"
627 let html_open_re = Pcre.regexp "^<html>\\s*$"
628 let html_close_re = Pcre.regexp "^</html>\\s*$"
629
630 let xhtml_of_content (dbh : Dbi.connection) hostid text =
631   (* Split the text into lines. *)
632   let lines = Pcre.split ~rex:split_lines_re text in
633
634   (* HTML blocks span multiple lines, so isolate these out first. *)
635   let rec loop = function
636     | [] -> []
637     | line :: xs when Pcre.pmatch ~rex:html_open_re line ->
638       (* Find the closing tag.  If not found, ignore opening tag. *)
639       let rec loop' acc = function
640         | [] -> None
641         | line :: xs when Pcre.pmatch ~rex:html_close_re line ->
642           Some (List.rev acc, xs)
643         | line :: xs ->
644             let acc = line :: acc in
645             loop' acc xs
646       in
647       (match loop' [] xs with
648          | Some (html, rest) ->
649              STpHTML html :: loop rest
650          | None ->
651              STpLine line :: loop xs)
652     | line :: xs ->
653         STpLine line :: loop xs
654   in
655   let lines = loop lines in
656
657   (* Iterate over the lines to isolate headers and paragraphs. *)
658   let lines =
659     List.map
660       (function
661          | STpLine line ->
662              if Pcre.pmatch ~rex:preformatted_re line then (
663                let subs = Pcre.exec ~rex:preformatted_re line in
664                let line = Pcre.get_substring subs 1 in
665                STPreformatted [line]
666              )
667              else if Pcre.pmatch ~rex:blank_re line then
668                STBlank
669              else if Pcre.pmatch ~rex:heading_re line then (
670                let subs = Pcre.exec ~rex:heading_re line in
671                let count = String.length (Pcre.get_substring subs 1) + 2 in
672                let line = Pcre.get_substring subs 2 in
673                STHeading (count, line)
674              )
675              else if Pcre.pmatch ~rex:unnumbered_re line then (
676                let subs = Pcre.exec ~rex:unnumbered_re line in
677                let line = Pcre.get_substring subs 2 in
678                STUnnumbered [line]
679              )
680              else if Pcre.pmatch ~rex:numbered_re line then (
681                let subs = Pcre.exec ~rex:numbered_re line in
682                let line = Pcre.get_substring subs 2 in
683                STNumbered [line]
684              ) else
685                STParagraph line
686          | STpHTML html ->
687              STHTML html
688       ) lines in
689
690   (* Aggregate paragraphs and lists. *)
691   let rec loop = function
692     | [] -> []
693     | STHeading (_, _) as h :: xs ->
694         h :: loop xs
695     | STUnnumbered lines1 :: STUnnumbered lines2 :: xs ->
696         loop (STUnnumbered (lines1 @ lines2) :: xs)
697     | STUnnumbered lines :: xs ->
698         STUnnumbered lines :: loop xs
699     | STNumbered lines1 :: STNumbered lines2 :: xs ->
700         loop (STNumbered (lines1 @ lines2) :: xs)
701     | STNumbered lines :: xs ->
702         STNumbered lines :: loop xs
703     | STPreformatted lines1 :: STPreformatted lines2 :: xs ->
704         loop (STPreformatted (lines1 @ lines2) :: xs)
705     | STPreformatted lines :: xs ->
706         STPreformatted lines :: loop xs
707     | STParagraph line1 :: STParagraph line2 :: xs ->
708         loop (STParagraph (line1 ^ " " ^ line2) :: xs)
709     | STParagraph line :: xs ->
710         STParagraph line :: loop xs
711     | STHTML html as h :: xs ->
712         h :: loop xs
713     | STBlank :: xs ->
714         loop xs
715   in
716   let lines = loop lines in
717
718   (* Convert lines to XHTML. *)
719   let lines =
720     List.map
721       (function
722          | STBlank -> assert false    (* Should never happen. *)
723          | STParagraph para ->
724              markup_paragraph dbh hostid para
725          | STHeading (level, text) ->
726              markup_heading dbh hostid level text
727          | STUnnumbered lines ->
728              markup_ul dbh hostid lines
729          | STNumbered lines ->
730              markup_ol dbh hostid lines
731          | STPreformatted lines ->
732              markup_pre lines
733          | STHTML html ->
734              let html' = String.concat "\n" html in
735              try
736                validate html';
737                html'
738              with
739                  Invalid_argument msg ->
740                    let msg = "Invalid HTML: " ^ msg in
741                    markup_pre (msg :: html)
742       ) lines in
743
744   (* Return the lines. *)
745   String.concat "\n" lines
746
747 (* Convert valid XHTML to plain text. *)
748 let text_re = Pcre.regexp "<[^>]+>"
749 let text_itempl = Pcre.subst " "
750
751 let text_of_xhtml xhtml =
752   Pcre.replace ~rex:text_re ~itempl:text_itempl xhtml