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