Support for users, roles, restrictions.
[cocanwiki.git] / scripts / admin / edit_emails.ml
1 (* COCANWIKI scripts.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: edit_emails.ml,v 1.2 2004/09/07 13:40:10 rich Exp $
5  *)
6
7 open Apache
8 open Registry
9 open Cgi
10 open Printf
11
12 open Merjisforwiki
13
14 open Cocanwiki
15 open Cocanwiki_ok
16
17 let split_re = Pcre.regexp "[\\r\\n,;]+"
18 let email_re = Pcre.regexp "(.*)<(.*)>"
19
20 let run r (q : cgi) (dbh : Dbi.connection) host_stuff _ =
21   let hostid = int_of_string (q#param "hostid") in
22
23   if q#param_true "cancel" then (
24     let _, hostname, _ = host_stuff in
25     q#redirect ("http://" ^ hostname ^ "/_bin/admin/host.cmo?hostid=" ^
26                 string_of_int hostid);
27     raise CgiExit
28   );
29
30   let emails = try q#param "emails" with Not_found -> "" in
31
32   (* It's very hard to verify email addresses.  Thus this script
33    * should not be exposed to untrusted users.
34    *)
35   let check_email str =
36     let name, email =
37       try
38         let subs = Pcre.exec ~rex:email_re str in
39         Pcre.get_substring subs 1, Pcre.get_substring subs 2
40       with
41           Not_found ->
42             "", str in
43
44     (* Trim whitespace. *)
45     trim name, trim email
46   in
47
48   let emails = Pcre.split ~rex:split_re emails in
49   let emails = List.map check_email emails in
50   let emails = List.filter ((<>) ("","")) emails in
51
52   (* Update the database. *)
53   let sth = dbh#prepare_cached
54               "delete from email_notify where hostid = ?" in
55   sth#execute [`Int hostid];
56   let sth = dbh#prepare_cached "insert into email_notify (hostid, email, name)
57                                 values (?, ?, ?)" in
58   List.iter (fun (name, email) ->
59                if name = "" then
60                  sth#execute [`Int hostid; `String email; `Null]
61                else
62                  sth#execute [`Int hostid; `String email; `String name])
63     emails;
64
65   (* Commit to the database. *)
66   dbh#commit ();
67
68   (* Print confirmation page. *)
69   let buttons = [
70     { StdPages.label = "OK";
71       StdPages.link = "/_bin/admin/host.cmo";
72       StdPages.method_ = None;
73       StdPages.params = [ "hostid", string_of_int hostid ] }
74   ] in
75
76   ok ~title:"Saved" ~buttons
77     q "Email notifications updated."
78
79 let () =
80   register_script run