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