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.5 2004/10/14 15:57:15 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 : Dbi.connection) 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 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"
89 q "Date or Message-ID header missing. Cannot handle this message. ";
93 (* Parse the date field. *)
96 let date = Netdate.parse date in
98 { Dbi.year = date.Netdate.year;
99 Dbi.month = date.Netdate.month;
100 Dbi.day = date.Netdate.day; },
101 { Dbi.hour = date.Netdate.hour;
102 Dbi.min = date.Netdate.minute;
103 Dbi.sec = date.Netdate.second;
105 Dbi.timezone = Some (date.Netdate.zone / 60); } in
108 Invalid_argument _ ->
109 failwith ("cannot parse date: " ^ date) in
111 (* Find the first thing in the In-Reply-To field which looks like a
116 let subs = Pcre.exec ~rex:irt_re in_reply_to in
117 Some (Pcre.get_substring subs 0)
121 (* References is a space-separated list of message IDs. Parse that up. *)
122 let references = Pcre.split ~rex:ws_re references in
124 (* Reverse the references list, because we most often want to see the
125 * head element (ie. the most immediate parent message).
127 let references = List.rev references in
129 (* If the head element of references != the in-reply-to message ID, then
133 match in_reply_to with
136 match references with
138 | m :: ms when m <> msgid -> msgid :: m :: ms
141 (* Does this message exist in the database already? If so, and overwrite
142 * is not specified, then silently skip this message. 'overwrite' becomes
143 * 'Some id' if we need to overwrite an existing message id in the database,
144 * else 'None' if this is a never-seen-before message.
147 let sth = dbh#prepare_cached "select id from messages
148 where hostid = ? and inet_message_id = ?" in
149 sth#execute [`Int hostid; `String inet_message_id];
151 let id = sth#fetch1int () in
152 if not overwrite then (
153 ok ~title:"Message exists"
154 q "Message already imported";
161 (* Save all of this in the database. *)
164 None -> (* Never-seen-before message. *)
167 "insert into messages (hostid, subject, inet_message_id,
168 message_date) values (?, ?, ?, ?)" in
169 sth#execute [`Int hostid; `String subject; `String inet_message_id;
170 `Timestamp (date, time)];
171 let msgid = sth#serial "messages_id_seq" in
175 "insert into msg_references (message_id, inet_message_id,
176 ordering) values (?, ?, ?)" in
177 let ordering = ref 0 in
178 List.iter (fun inet_message_id ->
179 incr ordering; let ordering = !ordering in
180 sth#execute [`Int msgid; `String inet_message_id;
181 `Int ordering]) references;
185 | Some msgid -> (* Overwrite an existing message. *)
186 (* All the fields in the messages table should be identical to
187 * last time we imported this message. Just return the msgid.
191 (* The message is referred to by a unique title: *)
192 let title = sprintf "Mail/%s (%d)" subject msgid in
194 (* Choose a suitable URL. *)
196 match Wikilib.generate_url_of_title dbh hostid title with
197 (* Duplicate URL is OK - eg. in the case where we are overwriting
198 * an already imported message.
200 Wikilib.GenURL_OK url | Wikilib.GenURL_Duplicate url -> url
201 | Wikilib.GenURL_TooShort | Wikilib.GenURL_BadURL ->
202 failwith "generate_url_of_title returned 'TooShort' or 'BadURL'" in
204 (* To create the page, we need a few more headers ... *)
205 let from = get_hdr "from" in
206 let to_hdr = get_hdr "to" in
207 let cc = get_hdr "cc" in
209 (* Create the page. Or edit it (if we're overwriting ...). *)
212 | None -> new_page (Title title)
213 | Some _ -> load_page dbh hostid ~url () in
214 let model = { model with redirect = "" } in
216 (* Create the first section (mail header). *)
220 hdr_template#set "subject" subject;
221 hdr_template#set "from" from;
222 hdr_template#set "inet_message_id" inet_message_id;
224 let yyyy, mm, dd = date.Dbi.year, date.Dbi.month, date.Dbi.day in
225 hdr_template#set "yyyy" (sprintf "%04d" yyyy);
226 hdr_template#set "mm" (sprintf "%02d" mm);
227 hdr_template#set "dd" (sprintf "%02d" dd);
228 hdr_template#set "short_month" (short_month mm);
231 List.map (fun addr -> [ "addr", Template.VarString addr ])
232 (Pcre.split ~rex:comma_re hdr)
234 let table = get_table to_hdr in
235 hdr_template#table "to" table;
236 hdr_template#conditional "has_to" (table <> []);
237 let table = get_table cc in
238 hdr_template#table "cc" table;
239 hdr_template#conditional "has_cc" (table <> []);
241 hdr_template#to_string
243 "", "mail_header", content in
245 (* Create the second section (mail body).
246 * XXX Very simple. Should be extended to understand attachments and
247 * convert them into file or image uploads.
250 let is_text_plain hdr =
252 let ct = hdr#field "content-type" in
253 String.starts_with ct "text/plain"
257 (* Find the first text/plain body. *)
258 let rec find_body = function
259 (header, `Body mime_body) when is_text_plain header ->
261 | (_, `Body _) -> raise Not_found
262 | (_, `Parts []) -> raise Not_found (* should never happen *)
263 | (_, `Parts (m :: _)) ->
266 (* Markup a plain text body. *)
267 let markup_body text =
268 (* Get all the titles from the database! We're going to exclude
269 * mail messages from this.
273 "select lower (title) from pages where hostid = ?
274 and url is not null and title not like 'Mail/%'" in
275 sth#execute [`Int hostid];
276 let links = sth#map (function [`String s] -> s | _ -> assert false) in
278 (* This code cannot find titles which are split across multiple lines.
281 let lines = Pcre.split ~rex:lines_re text in
283 (* We don't want to mark up the same link twice, so keep track of the
284 * titles we've already used.
290 let find str sub_lc =
292 String.find (String.lowercase str) sub_lc
294 String.Invalid_string -> -1
296 let rec loop line = function
299 let i = find line link in
300 if i >= 0 && not (List.mem link !used) then (
301 used := link :: !used;
302 let n = String.length link in
303 let n' = String.length line in
305 String.sub line 0 i ^
306 "[[" ^ String.sub line i n ^
307 "]]" ^ loop (String.sub line (i+n) (n' - (i+n))) links
313 loop line links) lines in
315 let lines = List.map trim lines in
317 List.map (fun line -> if line <> "" then line ^ " <br>" else "")
320 String.concat "\n" lines
325 let text = find_body msg in
326 let content = markup_body text in
330 "No plain text message body found" in
331 "Message", "mail_body", content in
333 (* Overwrite the first two sections of the current page, regardless of
335 * XXX We might consider more advanced strategies here: for example,
336 * use the divname to identify the old mail_header and mail_body and
337 * overwrite those, or insert them if they don't exist.
339 let contents = model.contents in
342 [] | [_] -> [ section0; section1 ]
343 | _ :: _ :: xs -> section0 :: section1 :: xs in
344 let model = { model with contents = contents } in
346 (* Write the page back. This can throw several exceptions, but we ignore
347 * them because we want to script to fail abruptly if any of these
348 * unexpected conditions arises.
350 save_page dbh hostid ~user ~r model;
352 (* Rebuild threads? *)
354 thread_mail dbh hostid date.Dbi.year date.Dbi.month;
356 (* Commit to the database. *)
361 q ("Message " ^ inet_message_id ^ " was imported.")
364 register_script ~restrict:[CanImportMail] run