Global replace 'raise CgiExit' -> 'return ()' to match a future version of mod_caml.
[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.11 2004/09/23 11:56:47 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 (* Server-wide settings.
38  *
39  * These are stored in a single row in the database in the table
40  * 'server_settings'.  You must restart the server if you change
41  * this row.
42  *
43  * It's not possible to read these at server start-up time because the
44  * Apache server is still running as 'root' and will not normally be
45  * allowed to access the database.  We thus read them at the earliest
46  * opportunity, in a request context, and cache the results.
47  *)
48 let server_settings_version =
49   let settings = ref None in
50   let get_settings (dbh : Dbi.connection) =
51     let sth = dbh#prepare "select version from server_settings" in
52     sth#execute [];
53     let s =
54       match sth#fetch1 () with
55         | [ `Int version ] -> version
56         | _ -> assert false in
57     sth#finish ();
58     settings := Some s;
59     s
60   in
61
62   let server_settings_version dbh =
63     let (version) =
64       match !settings with
65           None -> get_settings dbh
66         | Some settings -> settings in
67     version
68   in
69
70   server_settings_version
71
72 (* The [CgiExit] exception should be folded back into the base
73  * mod_caml code at some point.  It just causes the 'run' function to
74  * return at that point safely.  (XXX)
75  *)
76 exception CgiExit
77
78 let return () = raise CgiExit
79
80 (* Permissions and restrictions.
81  *
82  * Use the optional ~restrict parameter to register_script to restrict
83  * who can use the script.  For example:
84  *   register_script ~restrict:[CanEdit ; CanManageUsers] run
85  *)
86 type permissions_t = CanEdit | CanManageUsers | CanManageContacts
87                    | CanManageSite | CanEditGlobalCSS
88
89 (* The "user object". *)
90 type user_t = Anonymous                 (* Not logged in. *)
91             | User of int * string * permissions_t list
92                                         (* Userid, name, permissions. *)
93
94 let test_permission edit_anon perm user =
95   if perm = CanEdit && edit_anon then true
96   else match user with
97       Anonymous -> false
98     | User (_, _, perms) -> List.mem perm perms
99
100 let can_edit edit_anon = test_permission edit_anon CanEdit
101 let can_manage_users = test_permission false CanManageUsers
102 let can_manage_contacts = test_permission false CanManageContacts
103 let can_manage_site = test_permission false CanManageSite
104 let can_edit_global_css = test_permission false CanEditGlobalCSS
105
106 (* The "host object". *)
107 type host_t = { hostname : string;
108                 edit_anon : bool; }
109
110 (* Our wrapper around the standard [register_script] function.
111  *
112  * The optional ~restrict and ~anonymous parameters work as follows:
113  *
114  * By default (neither parameter given), anonymous or logged-in users
115  * at any level are permitted to run the script.
116  *
117  * If ~anonymous:false then a user must be logged in to use the script.
118  *
119  * If ~restrict contains a list of permissions (eg. CanEdit, etc.) then
120  * the user must have the ability to do AT LEAST ONE of those actions.
121  * (Note that this does not necessarily imply that the user must be
122  * logged in, because in some circumstances even anonymous users have
123  * the CanEdit permission - very typical for a wiki).
124  *
125  * If ~anonymous:false and ~restrict is given then the user must be
126  * logged in AND have the ability to do AT LEAST ONE of those actions.
127  *)
128 let register_script ?(restrict = []) ?(anonymous = true) run =
129   (* Actually register the script with the real [Registry] module. *)
130   register_script
131     (fun r ->
132        let q = new cgi r in
133        let dbh = _get_dbh r in
134
135        (* Get the host ID, by comparing the Host: header with the hostnames
136         * table in the database.
137         *)
138        let hostid, hostname, edit_anon =
139          let hostname = try Request.hostname r
140          with Not_found -> failwith "No ``Host:'' header in request" in
141          let hostname = String.lowercase hostname in
142
143          let sth =
144            dbh#prepare_cached
145              "select h.id, h.canonical_hostname, h.edit_anon
146                 from hostnames hn, hosts h
147                where hn.name = ? and hn.hostid = h.id" in
148          sth#execute [`String hostname];
149
150          try
151            (match sth#fetch1 () with
152                 [ `Int id; `String hostname; `Bool edit_anon ] ->
153                   id, hostname, edit_anon
154               | _ -> assert false)
155          with
156              Not_found ->
157                failwith ("Hostname ``" ^ hostname ^ "'' not found in " ^
158                          "the hosts/hostnames tables in the database.") in
159
160        (* Create the host object. *)
161        let host = { hostname = hostname; edit_anon = edit_anon; } in
162
163        (* Look for the user's cookie, and determine from this the user
164         * object.
165         *)
166        let user =
167          try
168            let cookie =
169              (* Allow the user to deliberately specify an extra "cookie"
170               * parameter, which we will send back as a cookie.  This is
171               * useful for "mail my password"-type scripts.
172               *)
173              if q#param_exists "cookie" then (
174                let value = q#param "cookie" in
175                let cookie = Cookie.cookie ~name:"auth" ~value ~path:"/" () in
176                Table.set (Request.headers_out r) "Set-Cookie" cookie#as_string;
177                value
178              ) else (
179                (* Normal cookie, from the headers. *)
180                let header = Table.get (Request.headers_in r) "Cookie" in
181                let cookies = Cookie.parse header in
182                let cookie =
183                  List.find (fun cookie -> cookie#name = "auth") cookies in
184                cookie#value
185              ) in
186
187            let sth =
188              dbh#prepare_cached
189                "select u.id, u.name, u.can_edit, u.can_manage_users,
190                        u.can_manage_contacts, u.can_manage_site,
191                        u.can_edit_global_css
192                   from usercookies uc, users u
193                  where uc.cookie = ? and uc.userid = u.id and u.hostid = ?" in
194            sth#execute [`String cookie; `Int hostid];
195            (match sth#fetch1 () with
196                 [ `Int userid; `String name;
197                   `Bool can_edit; `Bool can_manage_users;
198                   `Bool can_manage_contacts; `Bool can_manage_site;
199                   `Bool can_edit_global_css ] ->
200                   let perms = if can_edit then [ CanEdit ] else [] in
201                   let perms =
202                     if can_manage_users then CanManageUsers :: perms
203                     else perms in
204                   let perms =
205                     if can_manage_contacts then CanManageContacts :: perms
206                     else perms in
207                   let perms =
208                     if can_manage_site then CanManageSite :: perms
209                     else perms in
210                   let perms =
211                     if can_edit_global_css then CanEditGlobalCSS :: perms
212                     else perms in
213                   User (userid, name, perms)
214               | _ -> assert false)
215          with
216              Not_found -> Anonymous
217        in
218
219        (* If the ~restrict parameter is given, then we want to check that
220         * the user has sufficient permission to run this script.
221         *)
222        let permitted =
223          if not anonymous && user = Anonymous then false
224          else
225            match restrict with
226                [] -> true               (* empty list = no restrictions *)
227              | rs ->
228                  List.fold_left (||) false
229                    (List.map (fun r -> test_permission edit_anon r user) rs) in
230
231        if permitted then (
232          (* Call the actual CGI script. *)
233          try
234            run r q dbh hostid host user
235          with
236              CgiExit -> ()
237        ) else
238          error ~back_button:true
239            ~title:"Access denied"
240            q "You do not have permission to access this part of the site."
241     )
242
243 (* Convert a section name into something valid for use in <a name="...">
244  * XXX This breaks horribly for non-7-bit strings.
245  * XXX This is stuck here because we don't have a good place for it, and
246  * because it needs to be fixed for i18n compliance.
247  *)
248 let linkname_of_sectionname str =
249   let str = String.copy str in
250   for i = 0 to String.length str - 1 do
251     if not (isalnum str.[i]) then str.[i] <- '_'
252   done;
253   str