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 $
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.
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.
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.
30 open Cocanwiki_strings
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
36 type genurl_error_t = GenURL_OK of string
39 | GenURL_Duplicate of string
41 let nontrivial_re = Pcre.regexp ~flags:[`CASELESS] "[a-z0-9]"
43 let generate_url_of_title (dbh : Dbi.connection) hostid title =
44 (* Create a suitable URL from this title. *)
47 '\000' .. ' ' | '<' | '>' | '&' | '"' | '+' | '#' | '%'
49 | c -> Char.lowercase c) title in
51 (* Check URL is not too trivial. *)
52 if not (Pcre.pmatch ~rex:nontrivial_re url) then
54 (* URL cannot begin with '_'. *)
55 else if url.[0] = '_' then
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.
62 let sth = dbh#prepare_cached "select 1 from pages
63 where hostid = ? and url = ?" in
64 sth#execute [`Int hostid; `String url];
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
86 (* Convert Wiki markup to XHTML 1.0.
89 * Doesn't support multi-level bullet points. (XXX)
90 * Intra-page links. (XXX)
93 (* This matches any markup. *)
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 ^ "))(.*)")
99 (* This matches links only, and should be compatible with the link contained
100 * in the above regexp.
102 let link_re = Pcre.regexp "\\[\\[\\s*(.+?)\\s*(?:\\|(.+?)\\s*)?\\]\\]"
105 Pcre.regexp "^(image|thumb(?:nail)?):\\s*([a-z0-9][_a-z0-9]*\\.(?:jpg|jpeg|gif|ico|png))$"
107 Pcre.regexp "^file:\\s*([a-z0-9][-._a-z0-9]*)$"
109 let url_re = Pcre.regexp "^[a-z]+://"
110 let mailto_re = Pcre.regexp "^mailto:"
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
117 let tag name = function
119 | `String v -> " " ^ name ^ "=\"" ^ escape_html_tag v ^ "\""
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
128 let sql = "select id, " ^
129 (if is_thumb then "tn_width, tn_height"
130 else "width, height") ^
131 ", alt, title, longdesc, class
133 where hostid = ? and name = ?" in
134 let sth = dbh#prepare_cached sql in
135 sth#execute [`Int hostid; `String name];
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
147 let link = "/_image/" ^ escape_url name in
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 "") ^
153 string_of_int width ^
155 string_of_int height ^
157 escape_html_tag alt ^
160 tag "longdesc" longdesc ^
163 (if is_thumb then "</a>" else "")
166 (* Image not found. *)
167 "<a class=\"image_not_found\" " ^
168 "href=\"/_bin/upload_image_form.cmo?name=" ^
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
178 let sth = dbh#prepare_cached "select title
180 where hostid = ? and name = ?" in
181 sth#execute [`Int hostid; `String name];
185 match sth#fetch1 () with
186 [(`Null | `String _) as title] -> title
187 | _ -> assert false in
189 "<a href=\"/_file/" ^
198 (* File not found. *)
199 "<a class=\"file_not_found\" " ^
200 "href=\"/_bin/upload_file_form.cmo?name=" ^
206 (* Pcre changed behaviour between versions. Previously a non-capture
207 * would return "". Now it throws 'Not_found'.
210 try Pcre.get_substring subs 2
211 with Not_found -> "" in
212 let text = if text = "" then url else text in
214 (* XXX Escaping here is very hairy indeed. (See also the obscure_mailto
215 * function which performs some escaping ...)
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
225 (* Look up the 'URL' against the titles in the database and
226 * obtain the real URL.
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];
234 let url = sth#fetch1string () in
235 "/" ^ url, "internal", title
238 (* It might be a template page ... These pages don't
239 * exist in the template, but can be synthesized on the
242 let is_template_page url =
243 let sth = dbh#prepare_cached "select 1 from templates
247 sth#execute [`String url];
249 try sth#fetch1int () = 1 with Not_found -> false
252 if is_template_page url then
253 "/" ^ url, "internal", title
255 (* No, it really doesn't exist, so make it a link to
258 "/_bin/edit.cmo?title=" ^ escape_url url, "newpage", title
262 "\" class=\"" ^ clasz ^
263 "\" title=\"" ^ escape_html_tag title ^ "\">" ^
264 escape_html text ^ "</a>"
267 type find_t = FoundNothing
268 | FoundOpen of string * string * string
269 | FoundClose of string * string * string * string
270 | FoundLink of string * string * string
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"
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)
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)
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)
302 failwith ("bad regexp: markup is '" ^ markup ^ "'");
304 Not_found -> FoundNothing
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
313 let rec loop = function
314 | "", [] -> [""] (* base case *)
316 | text, ("nowiki" :: stack) ->
317 (*prerr_endline ("nowiki case: text = " ^ text);*)
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)
327 | "", (x :: xs) -> (* base case, popping the stack *)
328 "</" :: x :: ">" :: loop ("", xs)
331 (*prerr_endline ("text = " ^ text ^ ", stack empty");*)
333 (* Look for the earliest possible matching markup. Because the
334 * stack is empty, we're not looking for closing tags.
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 :: "</" :: escape_html elem :: ">" ::
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, [])
355 | text, ((x :: xs) as stack) ->
356 (*prerr_endline ("text = " ^ text ^ ", top of stack = " ^ x ^
357 ", stack size = " ^ string_of_int (List.length stack));*)
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) ->
380 escape_html first :: link :: loop (rest, stack)
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);*)
390 let markup_paragraph dbh hostid text =
391 "<p>" ^ _markup_paragraph dbh hostid text ^ "</p>"
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
397 let markup_ul dbh hostid lines =
399 String.concat "</li>\n<li>"
400 (List.map (fun t -> _markup_paragraph dbh hostid t) lines) ^
403 let markup_ol dbh hostid lines =
405 String.concat "</li>\n<li>"
406 (List.map (fun t -> _markup_paragraph dbh hostid t) lines) ^
409 let markup_pre lines =
411 String.concat "\n" (List.map Cgi_escape.escape_html lines) ^
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
420 let split_tags_re = Pcre.regexp ~flags:[`DOTALL] "<.*?>|[^<]+"
422 let open_attr_re = Pcre.regexp "^<([a-z]+)\\s*([^>]*?)(/?)>$"
423 let close_attr_re = Pcre.regexp "^</([a-z]+)>$"
425 let allowed_elements =
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", [];
435 "big", []; "small", []; "strike", []; "s", [];
436 "div", []; "span", [];
439 let headers = [ "h3", []; "h4", []; "h5", []; "h6", [] ] in
440 let links = [ "a", ["href"] ] in
441 let images = [ "img", ["src"; "alt"; "width"; "height"; "longdesc"] ] in
444 "form", [ "method"; "action"; "enctype" ];
445 "input", [ "name"; "value"; "type"; "size"; "maxlength" ];
446 "textarea", [ "name"; "rows"; "cols" ];
450 "table", []; "tr", [];
451 "th", [ "colspan"; "rowspan" ]; "td", [ "colspan"; "rowspan" ];
452 "thead", []; "tbody", []
455 basic @ headers @ links @ images @ forms @ tables
457 let standard_tags = [ "title"; "lang"; "class"; "id" ]
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.
465 if str = "" then [] (* Very common case. *)
467 let len = String.length str in
469 let fail () = invalid_arg ("bad tags near: " ^ truncate 20 str) in
471 let b = Buffer.create 100 in
473 if i < len && isalpha str.[i] then (
474 Buffer.add_char b str.[i];
481 let get_to_next_quote i =
482 let b = Buffer.create 100 in
484 if i < len && str.[i] <> '"' then (
485 Buffer.add_char b str.[i];
488 Buffer.contents b, (i+1)
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;
514 type valid_t = VText of string
515 | VOpen of string * (string * string) list
519 (* Split into attrs and non-attrs. We end up with a list like this:
520 * [ "<ul>"; "<li>"; "Some text"; "</li>"; ... ]
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
530 (* Parse up each attribute to get the tags. *)
535 if String.length str >= 2 && str.[0] = '<' then (
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
547 [VOpen (attr, tags); VClose attr]
549 (* Possible close attr. *)
550 let subs = Pcre.exec ~rex:close_attr_re str in
551 let attr = Pcre.get_substring subs 1 in
556 invalid_arg ("invalid element near " ^ truncate 20 str)
558 (* Ordinary text. Check no < or > characters. *)
559 (* XXX Check for valid "ed; entities. *)
560 if String.contains str '<' || String.contains str '>' then
562 ("unquoted '<' or '>' characters near " ^ truncate 20 str);
568 (* Check that opening/closing tags match. *)
569 let rec loop stack html =
570 match stack, html with
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 ->
578 | (attr1 :: stack), (VClose attr2 :: xs) ->
579 invalid_arg ("open/close elements don't match: " ^
580 truncate 20 attr1 ^ " and: " ^
582 | [], (VClose attr2 :: _) ->
583 invalid_arg ("close element with no matching open: " ^
585 | stack, (VText _ :: xs) ->
590 (* Now check that we only use the permitted elements. *)
591 let rec loop = function
593 | (VOpen (attr, tags)) :: xs ->
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;
603 invalid_arg ("this HTML attr is not allowed or contains a " ^
604 "tag which is not permitted: " ^
610 type preline_t = STpHTML of string list (* Block of HTML. *)
611 | STpLine of string (* A line. *)
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. *)
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*$"
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
634 (* HTML blocks span multiple lines, so isolate these out first. *)
635 let rec loop = function
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
641 | line :: xs when Pcre.pmatch ~rex:html_close_re line ->
642 Some (List.rev acc, xs)
644 let acc = line :: acc in
647 (match loop' [] xs with
648 | Some (html, rest) ->
649 STpHTML html :: loop rest
651 STpLine line :: loop xs)
653 STpLine line :: loop xs
655 let lines = loop lines in
657 (* Iterate over the lines to isolate headers and paragraphs. *)
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]
667 else if Pcre.pmatch ~rex:blank_re line then
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)
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
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
690 (* Aggregate paragraphs and lists. *)
691 let rec loop = function
693 | STHeading (_, _) as h :: 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 ->
716 let lines = loop lines in
718 (* Convert lines to XHTML. *)
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 ->
734 let html' = String.concat "\n" html in
739 Invalid_argument msg ->
740 let msg = "Invalid HTML: " ^ msg in
741 markup_pre (msg :: html)
744 (* Return the lines. *)
745 String.concat "\n" lines
747 (* Convert valid XHTML to plain text. *)
748 let text_re = Pcre.regexp "<[^>]+>"
749 let text_itempl = Pcre.subst " "
751 let text_of_xhtml xhtml =
752 Pcre.replace ~rex:text_re ~itempl:text_itempl xhtml