Contact form now identified by name, not ID field.
[cocanwiki.git] / scripts / cocanwiki.ml
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: cocanwiki.ml,v 1.12 2004/09/23 15:16:21 rich Exp $
5  *
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.
10  *
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.
15  *
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.
20  *)
21
22 open Apache
23 open Registry
24 open Cgi
25 open Printf
26
27 open Cocanwiki_ok
28 open Cocanwiki_strings
29
30 module Pool = DbiPool (Dbi_postgres)
31
32 (* This function is used to grab a database handle.  It's used in a couple
33  * of very special places, and is not for general consumption.
34  *)
35 let _get_dbh r = Pool.get r "cocanwiki"
36
37 (* The [CgiExit] exception should be folded back into the base
38  * mod_caml code at some point.  It just causes the 'run' function to
39  * return at that point safely.  (XXX)
40  *)
41 exception CgiExit
42
43 let return () = raise CgiExit
44
45 (* Permissions and restrictions.
46  *
47  * Use the optional ~restrict parameter to register_script to restrict
48  * who can use the script.  For example:
49  *   register_script ~restrict:[CanEdit ; CanManageUsers] run
50  *)
51 type permissions_t = CanEdit | CanManageUsers | CanManageContacts
52                    | CanManageSite | CanEditGlobalCSS
53
54 (* The "user object". *)
55 type user_t = Anonymous                 (* Not logged in. *)
56             | User of int * string * permissions_t list
57                                         (* Userid, name, permissions. *)
58
59 let test_permission edit_anon perm user =
60   if perm = CanEdit && edit_anon then true
61   else match user with
62       Anonymous -> false
63     | User (_, _, perms) -> List.mem perm perms
64
65 let can_edit edit_anon = test_permission edit_anon CanEdit
66 let can_manage_users = test_permission false CanManageUsers
67 let can_manage_contacts = test_permission false CanManageContacts
68 let can_manage_site = test_permission false CanManageSite
69 let can_edit_global_css = test_permission false CanEditGlobalCSS
70
71 (* The "host object". *)
72 type host_t = { hostname : string;
73                 edit_anon : bool; }
74
75 (* Our wrapper around the standard [register_script] function.
76  *
77  * The optional ~restrict and ~anonymous parameters work as follows:
78  *
79  * By default (neither parameter given), anonymous or logged-in users
80  * at any level are permitted to run the script.
81  *
82  * If ~anonymous:false then a user must be logged in to use the script.
83  *
84  * If ~restrict contains a list of permissions (eg. CanEdit, etc.) then
85  * the user must have the ability to do AT LEAST ONE of those actions.
86  * (Note that this does not necessarily imply that the user must be
87  * logged in, because in some circumstances even anonymous users have
88  * the CanEdit permission - very typical for a wiki).
89  *
90  * If ~anonymous:false and ~restrict is given then the user must be
91  * logged in AND have the ability to do AT LEAST ONE of those actions.
92  *)
93 let register_script ?(restrict = []) ?(anonymous = true) run =
94   (* Actually register the script with the real [Registry] module. *)
95   register_script
96     (fun r ->
97        let q = new cgi r in
98        let dbh = _get_dbh r in
99
100        (* Get the host ID, by comparing the Host: header with the hostnames
101         * table in the database.
102         *)
103        let hostid, hostname, edit_anon =
104          let hostname = try Request.hostname r
105          with Not_found -> failwith "No ``Host:'' header in request" in
106          let hostname = String.lowercase hostname in
107
108          let sth =
109            dbh#prepare_cached
110              "select h.id, h.canonical_hostname, h.edit_anon
111                 from hostnames hn, hosts h
112                where hn.name = ? and hn.hostid = h.id" in
113          sth#execute [`String hostname];
114
115          try
116            (match sth#fetch1 () with
117                 [ `Int id; `String hostname; `Bool edit_anon ] ->
118                   id, hostname, edit_anon
119               | _ -> assert false)
120          with
121              Not_found ->
122                failwith ("Hostname ``" ^ hostname ^ "'' not found in " ^
123                          "the hosts/hostnames tables in the database.") in
124
125        (* Create the host object. *)
126        let host = { hostname = hostname; edit_anon = edit_anon; } in
127
128        (* Look for the user's cookie, and determine from this the user
129         * object.
130         *)
131        let user =
132          try
133            let cookie =
134              (* Allow the user to deliberately specify an extra "cookie"
135               * parameter, which we will send back as a cookie.  This is
136               * useful for "mail my password"-type scripts.
137               *)
138              if q#param_exists "cookie" then (
139                let value = q#param "cookie" in
140                let cookie = Cookie.cookie ~name:"auth" ~value ~path:"/" () in
141                Table.set (Request.headers_out r) "Set-Cookie" cookie#as_string;
142                value
143              ) else (
144                (* Normal cookie, from the headers. *)
145                let header = Table.get (Request.headers_in r) "Cookie" in
146                let cookies = Cookie.parse header in
147                let cookie =
148                  List.find (fun cookie -> cookie#name = "auth") cookies in
149                cookie#value
150              ) in
151
152            let sth =
153              dbh#prepare_cached
154                "select u.id, u.name, u.can_edit, u.can_manage_users,
155                        u.can_manage_contacts, u.can_manage_site,
156                        u.can_edit_global_css
157                   from usercookies uc, users u
158                  where uc.cookie = ? and uc.userid = u.id and u.hostid = ?" in
159            sth#execute [`String cookie; `Int hostid];
160            (match sth#fetch1 () with
161                 [ `Int userid; `String name;
162                   `Bool can_edit; `Bool can_manage_users;
163                   `Bool can_manage_contacts; `Bool can_manage_site;
164                   `Bool can_edit_global_css ] ->
165                   let perms = if can_edit then [ CanEdit ] else [] in
166                   let perms =
167                     if can_manage_users then CanManageUsers :: perms
168                     else perms in
169                   let perms =
170                     if can_manage_contacts then CanManageContacts :: perms
171                     else perms in
172                   let perms =
173                     if can_manage_site then CanManageSite :: perms
174                     else perms in
175                   let perms =
176                     if can_edit_global_css then CanEditGlobalCSS :: perms
177                     else perms in
178                   User (userid, name, perms)
179               | _ -> assert false)
180          with
181              Not_found -> Anonymous
182        in
183
184        (* If the ~restrict parameter is given, then we want to check that
185         * the user has sufficient permission to run this script.
186         *)
187        let permitted =
188          if not anonymous && user = Anonymous then false
189          else
190            match restrict with
191                [] -> true               (* empty list = no restrictions *)
192              | rs ->
193                  List.fold_left (||) false
194                    (List.map (fun r -> test_permission edit_anon r user) rs) in
195
196        if permitted then (
197          (* Call the actual CGI script. *)
198          try
199            run r q dbh hostid host user
200          with
201              CgiExit -> ()
202        ) else
203          error ~back_button:true
204            ~title:"Access denied"
205            q "You do not have permission to access this part of the site."
206     )
207
208 (* Convert a section name into something valid for use in <a name="...">
209  * XXX This breaks horribly for non-7-bit strings.
210  * XXX This is stuck here because we don't have a good place for it, and
211  * because it needs to be fixed for i18n compliance.
212  *)
213 let linkname_of_sectionname str =
214   let str = String.copy str in
215   for i = 0 to String.length str - 1 do
216     if not (isalnum str.[i]) then str.[i] <- '_'
217   done;
218   str