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: mail_import.ml,v 1.14 2006/07/27 16:46:55 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.
35 open Cocanwiki_template
37 open Cocanwiki_strings
41 let irt_re = Pcre.regexp "<.*?>"
42 let ws_re = Pcre.regexp "\\s+"
43 let comma_re = Pcre.regexp "\\s*,\\s*"
44 let lines_re = Pcre.regexp "\\r?\\n"
46 let run r (q : cgi) dbh hostid _ user =
47 let hdr_template = get_template dbh hostid "mail_import_header.txt" in
49 (* Overwrite old messages? *)
50 let overwrite = q#param_true "overwrite" in
51 (* Rebuild index after importing this one message? *)
52 let rebuild = q#param_true "rebuild" in
54 (* Get the uploaded file. *)
57 let upload = q#upload "file" in
61 error ~back_button:true ~title:"No message"
62 dbh hostid q "No message was uploaded.";
65 (* Parse the message. *)
68 (new input_string file)
70 let stm = new input_stream ch in
71 read_mime_message stm) in
73 (* Get the mail header for easy access. *)
76 (* Get the interesting headers which will go into the database. *)
77 let get_hdr name = try hdr#field name with Not_found -> "" in
78 let subject = get_hdr "subject" in
79 let inet_message_id = get_hdr "message-id" in
80 let date = get_hdr "date" in
81 let references = get_hdr "references" in
82 let in_reply_to = get_hdr "in-reply-to" in
84 (* If the message doesn't have a Date or Message-ID header, then we
85 * cannot thread it, so give up.
87 if date = "" || inet_message_id = "" then (
88 error ~back_button:true ~title:"Headers missing"
90 "Date or Message-ID header missing. Cannot handle this message. ";
94 (* Can't handle funny characters in subject lines - remove them. *)
95 let subject = String.map (fun c ->
96 if Char.code c < 32 then ' ' else c) subject in
98 (* Parse the date field. *)
101 let date = Netdate.parse date in
102 let cal = Calendar.make
108 date.Netdate.second in
109 let tz = Time_Zone.UTC_Plus (date.Netdate.zone / 60) in
112 Invalid_argument _ ->
113 failwith ("cannot parse date: " ^ date) in
115 (* Find the first thing in the In-Reply-To field which looks like a
120 let subs = Pcre.exec ~rex:irt_re in_reply_to in
121 Some (Pcre.get_substring subs 0)
125 (* References is a space-separated list of message IDs. Parse that up. *)
126 let references = Pcre.split ~rex:ws_re references in
128 (* Reverse the references list, because we most often want to see the
129 * head element (ie. the most immediate parent message).
131 let references = List.rev references in
133 (* If the head element of references != the in-reply-to message ID, then
137 match in_reply_to with
140 match references with
142 | m :: ms when m <> msgid -> msgid :: m :: ms
145 (* Does this message exist in the database already? If so, and overwrite
146 * is not specified, then silently skip this message. 'overwrite' becomes
147 * 'Some id' if we need to overwrite an existing message id in the database,
148 * else 'None' if this is a never-seen-before message.
151 let rows = PGSQL(dbh)
152 "select id from messages
153 where hostid = $hostid and inet_message_id = $inet_message_id" in
156 if not overwrite then (
157 ok ~title:"Message exists"
158 dbh hostid q "Message already imported";
163 | _ -> assert false in
165 (* Save all of this in the database. *)
168 None -> (* Never-seen-before message. *)
170 "insert into messages (hostid, subject, inet_message_id,
172 values ($hostid, $subject, $inet_message_id, $message_date)";
173 let msgid = PGOCaml.serial4 dbh "messages_id_seq" in
175 let ordering = ref 0 in
176 List.iter (fun inet_message_id ->
177 incr ordering; let ordering = Int32.of_int !ordering in
179 "insert into msg_references (message_id,
180 inet_message_id, ordering)
181 values ($msgid, $inet_message_id, $ordering)"
186 | Some msgid -> (* Overwrite an existing message. *)
187 (* All the fields in the messages table should be identical to
188 * last time we imported this message. Just return the msgid.
192 (* The message is referred to by a unique title.
193 * NB. Do not change this unique title - it is also used during thread
196 let title = sprintf "Mail/%s (%ld)" subject msgid in
198 (* Choose a suitable URL. *)
200 match Wikilib.generate_url_of_title r dbh hostid title with
201 (* Duplicate URL is OK - eg. in the case where we are overwriting
202 * an already imported message.
204 Wikilib.GenURL_OK url | Wikilib.GenURL_Duplicate url -> url
205 | Wikilib.GenURL_TooShort | Wikilib.GenURL_BadURL ->
206 failwith "generate_url_of_title returned 'TooShort' or 'BadURL'" in
208 (* To create the page, we need a few more headers ... *)
209 let from = get_hdr "from" in
210 let to_hdr = get_hdr "to" in
211 let cc = get_hdr "cc" in
213 (* Create the page. Or edit it (if we're overwriting ...). *)
216 | None -> new_page (Title title)
217 | Some _ -> load_page dbh hostid ~url () in
218 let model = { model with redirect = None } in
220 (* Create the first section (mail header). *)
224 hdr_template#set "subject" subject;
225 hdr_template#set "from" from;
226 hdr_template#set "inet_message_id" inet_message_id;
228 let date = fst message_date in
229 hdr_template#set "yyyy" (Printer.CalendarPrinter.sprint "%Y" date);
230 hdr_template#set "mm" (Printer.CalendarPrinter.sprint "%m" date);
231 hdr_template#set "dd" (Printer.CalendarPrinter.sprint "%d" date);
232 hdr_template#set "short_month"
233 (Printer.short_name_of_month (Calendar.month date));
236 List.map (fun addr -> [ "addr", Template.VarString addr ])
237 (Pcre.split ~rex:comma_re hdr)
239 let table = get_table to_hdr in
240 hdr_template#table "to" table;
241 hdr_template#conditional "has_to" (table <> []);
242 let table = get_table cc in
243 hdr_template#table "cc" table;
244 hdr_template#conditional "has_cc" (table <> []);
246 hdr_template#to_string
248 None, Some "mail_header", None, content in
250 (* Create the second section (mail body).
251 * XXX Very simple. Should be extended to understand attachments and
252 * convert them into file or image uploads.
255 let is_text_plain hdr =
257 let ct = hdr#field "content-type" in
258 String.starts_with ct "text/plain"
262 (* Find the first text/plain body. *)
263 let rec find_body = function
264 (header, `Body mime_body) when is_text_plain header ->
266 | (_, `Body _) -> raise Not_found
267 | (_, `Parts []) -> raise Not_found (* should never happen *)
268 | (_, `Parts (m :: _)) ->
271 (* Markup a plain text body. *)
272 let markup_body text =
273 (* Get all the titles from the database! We're going to exclude
274 * mail messages from this.
278 "select lower (title) from pages where hostid = $hostid
279 and url is not null and title not like 'Mail/%'" in
280 let links = List.map Option.get links in
282 (* This code cannot find titles which are split across multiple lines.
285 let lines = Pcre.split ~rex:lines_re text in
287 (* We don't want to mark up the same link twice, so keep track of the
288 * titles we've already used.
294 let find str sub_lc =
296 String.find (String.lowercase str) sub_lc
300 let rec loop line = function
303 let i = find line link in
304 if i >= 0 && not (List.mem link !used) then (
305 used := link :: !used;
306 let n = String.length link in
307 let n' = String.length line in
309 String.sub line 0 i ^
310 "[[" ^ String.sub line i n ^
311 "]]" ^ loop (String.sub line (i+n) (n' - (i+n))) links
317 loop line links) lines in
319 let lines = List.map trim lines in
320 let lines = List.map (fun line -> line ^ "<br>") lines in
322 String.concat "\n" lines
327 let text = find_body msg in
328 let content = markup_body text in
332 "No plain text message body found" in
333 Some "Message", Some "mail_body", None, content in
335 (* Overwrite the first two sections of the current page, regardless of
337 * XXX We might consider more advanced strategies here: for example,
338 * use the divname to identify the old mail_header and mail_body and
339 * overwrite those, or insert them if they don't exist.
341 let contents = model.contents_ in
344 | [] | [_] -> [ section0; section1 ]
345 | _ :: _ :: xs -> section0 :: section1 :: xs in
346 let model = { model with contents_ = contents } in
348 (* Write the page back. This can throw several exceptions, but we ignore
349 * them because we want to script to fail abruptly if any of these
350 * unexpected conditions arises.
352 ignore (save_page r dbh hostid ~user model);
354 (* Rebuild threads? *)
356 thread_mail r dbh hostid ~user
357 (Calendar.year (fst message_date))
358 (Date.int_of_month (Calendar.month (fst message_date)));
360 (* Commit to the database. *)
365 dbh hostid q ("Message " ^ inet_message_id ^ " was imported.")
368 register_script ~restrict:[CanImportMail] run