d1f8ec6c993ccf4258749e62da3e9d1a082ae3e9
[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.9 2006/03/27 16:43:44 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 (* The "host object". *)
31 type host_t = { hostname : string;
32                 canonical_hostname : string;
33                 edit_anon : bool;
34                 view_anon : bool }
35
36 (* Permissions and restrictions.
37  *
38  * Use the optional ~restrict parameter to register_script to restrict
39  * who can use the script.  For example:
40  *   register_script ~restrict:[CanEdit ; CanManageUsers] run
41  *)
42 type permissions_t = CanView | CanEdit | CanManageUsers | CanManageContacts
43                    | CanManageSite | CanEditGlobalCSS | CanImportMail
44
45 (* User preferences and other settings (some cannot be changed by the user). *)
46 type prefs_t = {
47   email : string option;                (* Email address. *)
48   email_notify : bool;                  (* Email notification. *)
49 }
50
51 (* The "user object". *)
52 type user_t = Anonymous                 (* Not logged in. *)
53             | User of int32 * string * permissions_t list * prefs_t
54                                         (* Userid, name, perms, prefs. *)
55
56 let test_permission {edit_anon = edit_anon; view_anon = view_anon} perm user =
57   if perm = CanEdit && edit_anon then true
58   else if perm = CanView && view_anon then true
59   else match user with
60       Anonymous -> false
61     | User (_, _, perms, _) -> List.mem perm perms
62
63 let can_edit host = test_permission host CanEdit
64 let can_manage_users host = test_permission host CanManageUsers
65 let can_manage_contacts host = test_permission host CanManageContacts
66 let can_manage_site host = test_permission host CanManageSite
67 let can_edit_global_css host = test_permission host CanEditGlobalCSS
68 let can_import_mail host = test_permission host CanImportMail
69
70 (* Our wrapper around the standard [register_script] function.
71  *
72  * The optional ~restrict and ~anonymous parameters work as follows:
73  *
74  * By default (neither parameter given), anonymous or logged-in users
75  * at any level are permitted to run the script.
76  *
77  * If ~anonymous:false then a user must be logged in to use the script.
78  *
79  * If ~restrict contains a list of permissions (eg. CanEdit, etc.) then
80  * the user must have the ability to do AT LEAST ONE of those actions.
81  * (Note that this does not necessarily imply that the user must be
82  * logged in, because in some circumstances even anonymous users have
83  * the CanEdit permission - very typical for a wiki).
84  *
85  * If ~anonymous:false and ~restrict is given then the user must be
86  * logged in AND have the ability to do AT LEAST ONE of those actions.
87  *)
88 let register_script ?(restrict = []) ?(anonymous = true) run =
89   (* Actually register the script with the real [Registry] module. *)
90   register_script
91     (fun r ->
92        let q = new cgi r in
93
94        (* XXX Database pooling. *)
95        let dbh = PGOCaml.connect ~database:"cocanwiki" () in
96        PGOCaml.begin_work dbh;
97
98        let exn =
99          try
100            (* Get the host ID, by comparing the Host: header with the hostnames
101             * table in the database.
102             *)
103            let hostid, hostname, canonical_hostname, edit_anon, view_anon =
104              let hostname = try Request.hostname r
105              with Not_found ->
106                error ~back_button:true
107                  ~title:"Browser problem" dbh (-1l) q
108                  ("Your browser didn't send a \"Host\" header as part of " ^
109                     "the HTTP request.  Unfortunately this web server cannot "^
110                     "handle HTTP requests without a \"Host\" header.");
111                return () in
112              let hostname = String.lowercase hostname in
113
114              let rows =
115                PGSQL(dbh)
116                  "select h.id, h.canonical_hostname, h.edit_anon, h.view_anon
117                     from hostnames hn, hosts h
118                    where hn.name = $hostname and hn.hostid = h.id" in
119
120              match rows with
121              | [id, canonical_hostname, edit_anon, view_anon] ->
122                  id, hostname, canonical_hostname, edit_anon, view_anon
123              | [] ->
124                error ~back_button:true
125                  ~title:"Unknown website" dbh (-1l) q
126                  ("No website called \"" ^ hostname ^ "\" can be found.  " ^
127                   "If you are the administrator of this site, check that " ^
128                   "the hostname is listed in the \"hostnames\" table " ^
129                   "in the database.");
130                  return ()
131              | _ -> assert false in
132
133            (* Create the host object. *)
134            let host = { hostname = hostname;
135                         canonical_hostname = canonical_hostname;
136                         edit_anon = edit_anon;
137                         view_anon = view_anon } in
138
139            (* Look for the user's cookie, and determine from this the user
140             * object.
141             *)
142            let user =
143              try
144                let cookie =
145                  (* Allow the user to deliberately specify an extra "cookie"
146                   * parameter, which we will send back as a cookie.  This is
147                   * useful for "mail my password"-type scripts.
148                   *)
149                  if q#param_exists "cookie" then (
150                    let value = q#param "cookie" in
151                    let cookie = Cookie.cookie "auth" value ~path:"/" in
152                    Table.set (Request.headers_out r)
153                      "Set-Cookie" cookie#to_string;
154                    value
155                  ) else (
156                    (* Normal cookie, from the headers. *)
157                    let header = Table.get (Request.headers_in r) "Cookie" in
158                    let cookies = Cookie.parse header in
159                    let cookie =
160                      List.find (fun cookie -> cookie#name = "auth") cookies in
161                    cookie#value
162                  ) in
163
164                let rows =
165                  PGSQL(dbh)
166                    "select u.id, u.name, u.can_edit, u.can_manage_users,
167                            u.can_manage_contacts, u.can_manage_site,
168                            u.can_edit_global_css, u.can_import_mail,
169                            u.email, u.email_notify
170                       from usercookies uc, users u
171                      where uc.cookie = $cookie
172                        and uc.userid = u.id
173                        and u.hostid = $hostid" in
174                match rows with
175                | [userid, name, can_edit, can_manage_users,
176                   can_manage_contacts, can_manage_site,
177                   can_edit_global_css, can_import_mail,
178                   email, email_notify] ->
179                    (* Every logged in user can view. *)
180                    let perms = [CanView] in
181                    let perms =
182                      if can_edit then CanEdit :: perms
183                      else perms in
184                    let perms =
185                      if can_manage_users then CanManageUsers :: perms
186                      else perms in
187                    let perms =
188                      if can_manage_contacts then CanManageContacts :: perms
189                      else perms in
190                    let perms =
191                      if can_manage_site then CanManageSite :: perms
192                      else perms in
193                    let perms =
194                      if can_edit_global_css then CanEditGlobalCSS :: perms
195                      else perms in
196                    let perms =
197                      if can_import_mail then CanImportMail :: perms
198                      else perms in
199                    (* Preferences. *)
200                    let prefs = { email = email;
201                                  email_notify = email_notify; } in
202                    User (userid, name, perms, prefs)
203                | [] -> raise Not_found
204                | _ -> assert false
205              with
206                Not_found -> Anonymous in
207
208            (* If the ~restrict parameter is given, then we want to check that
209             * the user has sufficient permission to run this script.
210             *)
211            let permitted =
212              if not anonymous && user = Anonymous then false
213              else
214                match restrict with
215                | [] -> true             (* empty list = no restrictions *)
216                | rs ->
217                    List.fold_left (||) false
218                      (List.map (fun r -> test_permission host r user) rs) in
219
220            if permitted then (
221              (* Call the actual CGI script. *)
222              run r q dbh hostid host user
223            ) else (
224              if user = Anonymous then (
225                (* Not logged in and no permission to do the requested action,
226                 * so redirect to the login script.  If possible set the
227                 * redirect parameter so that we return to the right URL.
228                 *)
229                let redirect =
230                  try
231                    (* If we passed through mod_rewrite, then it saved the
232                     * unmodified original URL in a subprocess environment
233                     * variable called SCRIPT_URL:
234                     *)
235                    let tbl = Request.subprocess_env r in
236                    Some (Table.get tbl "SCRIPT_URL")
237                  with
238                    Not_found ->
239                      try
240                        (* Otherwise try the ordinary uri field
241                         * in request_rec.
242                         *)
243                        Some (Request.uri r)
244                      with Not_found ->
245                        None in
246
247                let url =
248                  "http://" ^ hostname ^ "/_login" ^
249                    match redirect with
250                    | None -> ""
251                    | Some url -> "?redirect=" ^ Cgi_escape.escape_url url in
252                q#redirect url
253              ) else
254                error ~back_button:true
255                  ~title:"Access denied"
256                  dbh hostid q
257                  "You do not have permission to access this part of the site."
258            );
259
260            None (* no exception *)
261          with
262            exn -> Some exn in
263
264        (* XXX Connection pooling - see above. *)
265        PGOCaml.close dbh;
266
267        (* May re-raise the caught exception. *)
268        Option.may raise exn
269     )
270
271 (* Convert a section name into something valid for use in <a name="...">
272  * XXX This breaks horribly for non-7-bit strings.
273  * XXX This is stuck here because we don't have a good place for it, and
274  * because it needs to be fixed for i18n compliance.
275  *)
276 let linkname_of_sectionname str =
277   let str = String.copy str in
278   for i = 0 to String.length str - 1 do
279     if not (isalnum str.[i]) then str.[i] <- '_'
280   done;
281   str
282
283 (* List of extensions currently registered. *)
284 type extension_t = PGOCaml.pa_pg_data PGOCaml.t -> int32 -> string -> string
285 let extensions = ref ([] : (string * extension_t) list)
286
287 (* Maximum degree of redirection. *)
288 let max_redirect = 4