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