Added the framework to allow us to populate standards parts of the
[cocanwiki.git] / scripts / admin / edit_hostnames.ml
1 (* COCANWIKI scripts.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: edit_hostnames.ml,v 1.3 2004/09/07 14:58:34 rich Exp $
5  *)
6
7 open Apache
8 open Registry
9 open Cgi
10 open Printf
11
12 open Cocanwiki
13 open Cocanwiki_ok
14 open Cocanwiki_strings
15
16 let split_re = Pcre.regexp "[\\s,;]+"
17
18 let run r (q : cgi) (dbh : Dbi.connection) host_stuff _ =
19   let hostid = int_of_string (q#param "hostid") in
20
21   if q#param_true "cancel" then (
22     let _, hostname, _ = host_stuff in
23     q#redirect ("http://" ^ hostname ^ "/_bin/admin/host.cmo?hostid=" ^
24                 string_of_int hostid);
25     raise CgiExit
26   );
27
28   let canonical_hostname = q#param "canonical_hostname" in
29   let hostnames = try q#param "hostnames" with Not_found -> "" in
30
31   (* In theory we could verify characters in hostnames, and call
32    * error / raise CgiExit if the format is incorrect.  However
33    * it's probably best to assume the sysadmin knows what they're up to
34    * here.  If this script is allowed to be accessed by untrusted users,
35    * then this has security implications.
36    *)
37   let check_hostname h =
38     let h = trim h in                   (* Trim whitespace. *)
39     let h = String.lowercase h in       (* Lowercase. *)
40     h
41   in
42
43   let canonical_hostname = check_hostname canonical_hostname in
44   let hostnames = Pcre.split ~rex:split_re hostnames in
45   let hostnames = List.map check_hostname hostnames in
46   let hostnames = List.filter ((<>) "") hostnames in
47
48   (* Update the database. *)
49   let sth = dbh#prepare_cached
50               "set constraints \"hosts_hostname_cn\" deferred" in
51   sth#execute [];
52   let sth = dbh#prepare_cached "update hosts set canonical_hostname = ?
53                                  where id = ?" in
54   sth#execute [`String canonical_hostname; `Int hostid];
55   let sth = dbh#prepare_cached "delete from hostnames where hostid = ?" in
56   sth#execute [`Int hostid];
57   let sth = dbh#prepare_cached "insert into hostnames (hostid, name)
58                                 values (?, ?)" in
59   sth#execute [`Int hostid; `String canonical_hostname];
60   List.iter (fun name ->
61                sth#execute [`Int hostid; `String name]) hostnames;
62
63   (* Commit to the database. *)
64   dbh#commit ();
65
66   (* Print confirmation page. *)
67   let buttons = [
68     { StdPages.label = "OK";
69       StdPages.link = "/_bin/admin/host.cmo";
70       StdPages.method_ = None;
71       StdPages.params = [ "hostid", string_of_int hostid ] }
72   ] in
73
74   ok ~title:"Saved" ~buttons
75     q "Hostnames updated."
76
77 let () =
78   register_script run