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