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