Use Dbi_postgresql module.
[cocanwiki.git] / scripts / lib / 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.6 2005/11/16 10:45:41 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_postgresql)
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 "host object". *)
38 type host_t = { hostname : string;
39                 canonical_hostname : string;
40                 edit_anon : bool;
41                 view_anon : bool }
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 = CanView | CanEdit | CanManageUsers | CanManageContacts
50                    | CanManageSite | CanEditGlobalCSS | CanImportMail
51
52 (* User preferences and other settings (some cannot be changed by the user). *)
53 type prefs_t = {
54   email : string option;                (* Email address. *)
55   email_notify : bool;                  (* Email notification. *)
56 }
57
58 (* The "user object". *)
59 type user_t = Anonymous                 (* Not logged in. *)
60             | User of int * string * permissions_t list * prefs_t
61                                         (* Userid, name, perms, prefs. *)
62
63 let test_permission {edit_anon = edit_anon; view_anon = view_anon} perm user =
64   if perm = CanEdit && edit_anon then true
65   else if perm = CanView && view_anon then true
66   else match user with
67       Anonymous -> false
68     | User (_, _, perms, _) -> List.mem perm perms
69
70 let can_edit host = test_permission host CanEdit
71 let can_manage_users host = test_permission host CanManageUsers
72 let can_manage_contacts host = test_permission host CanManageContacts
73 let can_manage_site host = test_permission host CanManageSite
74 let can_edit_global_css host = test_permission host CanEditGlobalCSS
75 let can_import_mail host = test_permission host CanImportMail
76
77 (* Our wrapper around the standard [register_script] function.
78  *
79  * The optional ~restrict and ~anonymous parameters work as follows:
80  *
81  * By default (neither parameter given), anonymous or logged-in users
82  * at any level are permitted to run the script.
83  *
84  * If ~anonymous:false then a user must be logged in to use the script.
85  *
86  * If ~restrict contains a list of permissions (eg. CanEdit, etc.) then
87  * the user must have the ability to do AT LEAST ONE of those actions.
88  * (Note that this does not necessarily imply that the user must be
89  * logged in, because in some circumstances even anonymous users have
90  * the CanEdit permission - very typical for a wiki).
91  *
92  * If ~anonymous:false and ~restrict is given then the user must be
93  * logged in AND have the ability to do AT LEAST ONE of those actions.
94  *)
95 let register_script ?(restrict = []) ?(anonymous = true) run =
96   (* Actually register the script with the real [Registry] module. *)
97   register_script
98     (fun r ->
99        let q = new cgi r in
100        let dbh = _get_dbh r in
101
102        (* Get the host ID, by comparing the Host: header with the hostnames
103         * table in the database.
104         *)
105        let hostid, hostname, canonical_hostname, edit_anon, view_anon =
106          let hostname = try Request.hostname r
107          with Not_found ->
108            error ~back_button:true
109              ~title:"Browser problem" q
110              ("Your browser didn't send a \"Host\" header as part of " ^
111               "the HTTP request.  Unfortunately this web server cannot " ^
112               "handle HTTP requests without a \"Host\" header.");
113            return () in
114          let hostname = String.lowercase hostname in
115
116          let sth =
117            dbh#prepare_cached
118              "select h.id, h.canonical_hostname, h.edit_anon, h.view_anon
119                 from hostnames hn, hosts h
120                where hn.name = ? and hn.hostid = h.id" in
121          sth#execute [`String hostname];
122
123          try
124            (match sth#fetch1 () with
125                 [ `Int id; `String canonical_hostname;
126                   `Bool edit_anon; `Bool view_anon ] ->
127                   id, hostname, canonical_hostname, edit_anon, view_anon
128               | _ -> assert false)
129          with
130              Not_found ->
131                error ~back_button:true
132                  ~title:"Unknown website" q
133                  ("No website called \"" ^ hostname ^ "\" can be found.  " ^
134                   "If you are the administrator of this site, check that " ^
135                   "the hostname is listed in the \"hostnames\" table " ^
136                   "in the database.");
137                return () in
138
139        (* Create the host object. *)
140        let host = { hostname = hostname;
141                     canonical_hostname = canonical_hostname;
142                     edit_anon = edit_anon;
143                     view_anon = view_anon } in
144
145        (* Look for the user's cookie, and determine from this the user
146         * object.
147         *)
148        let user =
149          try
150            let cookie =
151              (* Allow the user to deliberately specify an extra "cookie"
152               * parameter, which we will send back as a cookie.  This is
153               * useful for "mail my password"-type scripts.
154               *)
155              if q#param_exists "cookie" then (
156                let value = q#param "cookie" in
157                let cookie = Cookie.cookie "auth" value ~path:"/" in
158                Table.set (Request.headers_out r) "Set-Cookie" cookie#to_string;
159                value
160              ) else (
161                (* Normal cookie, from the headers. *)
162                let header = Table.get (Request.headers_in r) "Cookie" in
163                let cookies = Cookie.parse header in
164                let cookie =
165                  List.find (fun cookie -> cookie#name = "auth") cookies in
166                cookie#value
167              ) in
168
169            let sth =
170              dbh#prepare_cached
171                "select u.id, u.name, u.can_edit, u.can_manage_users,
172                        u.can_manage_contacts, u.can_manage_site,
173                        u.can_edit_global_css, u.can_import_mail,
174                        u.email, u.email_notify
175                   from usercookies uc, users u
176                  where uc.cookie = ? and uc.userid = u.id and u.hostid = ?" in
177            sth#execute [`String cookie; `Int hostid];
178            (match sth#fetch1 () with
179                 [ `Int userid; `String name;
180                   `Bool can_edit; `Bool can_manage_users;
181                   `Bool can_manage_contacts; `Bool can_manage_site;
182                   `Bool can_edit_global_css; `Bool can_import_mail;
183                   (`Null | `String _) as email; `Bool email_notify ] ->
184                   (* Every logged in user can view. *)
185                   let perms = [CanView] in
186                   let perms =
187                     if can_edit then CanEdit :: perms
188                     else perms in
189                   let perms =
190                     if can_manage_users then CanManageUsers :: perms
191                     else perms in
192                   let perms =
193                     if can_manage_contacts then CanManageContacts :: perms
194                     else perms in
195                   let perms =
196                     if can_manage_site then CanManageSite :: perms
197                     else perms in
198                   let perms =
199                     if can_edit_global_css then CanEditGlobalCSS :: perms
200                     else perms in
201                   let perms =
202                     if can_import_mail then CanImportMail :: perms
203                     else perms in
204                   (* Preferences. *)
205                   let email =
206                     match email with
207                         `Null -> None
208                       | `String email -> Some email in
209                   let prefs = { email = email;
210                                 email_notify = email_notify; } in
211                   User (userid, name, perms, prefs)
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 host r user) rs) in
228
229        if permitted then (
230          (* Call the actual CGI script. *)
231          run r q dbh hostid host user
232        ) else (
233          if user = Anonymous then
234            q#redirect ("http://" ^ hostname ^ "/_login")
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
242 (* Convert a section name into something valid for use in <a name="...">
243  * XXX This breaks horribly for non-7-bit strings.
244  * XXX This is stuck here because we don't have a good place for it, and
245  * because it needs to be fixed for i18n compliance.
246  *)
247 let linkname_of_sectionname str =
248   let str = String.copy str in
249   for i = 0 to String.length str - 1 do
250     if not (isalnum str.[i]) then str.[i] <- '_'
251   done;
252   str
253
254 (* List of extensions currently registered. *)
255 type extension_t = Dbi.connection -> int -> string -> string
256 let extensions = ref ([] : (string * extension_t) list)
257
258 (* Maximum degree of redirection. *)
259 let max_redirect = 4