Very primitive, but working, RSS feeds.
[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.8 2004/09/20 15:34:36 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 [CgiExit] exception should be folded back into the base
38  * mod_caml code at some point.  It just causes the 'run' function to
39  * return at that point safely.  (XXX)
40  *)
41 exception CgiExit
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 = CanEdit | CanManageUsers | CanManageContacts
50
51 (* The "user object". *)
52 type user_t = Anonymous                 (* Not logged in. *)
53             | User of int * string * permissions_t list
54                                         (* Userid, name, permissions. *)
55
56 let test_permission edit_anon perm user =
57   if perm = CanEdit && edit_anon then true
58   else match user with
59       Anonymous -> false
60     | User (_, _, perms) -> List.mem perm perms
61
62 let can_edit edit_anon = test_permission edit_anon CanEdit
63 let can_manage_users = test_permission false CanManageUsers
64 let can_manage_contacts = test_permission false CanManageContacts
65
66 (* The "host object". *)
67 type host_t = { hostname : string;
68                 edit_anon : bool; }
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        let dbh = _get_dbh r in
94
95        (* Get the host ID, by comparing the Host: header with the hostnames
96         * table in the database.
97         *)
98        let hostid, hostname, edit_anon =
99          let hostname = try Request.hostname r
100          with Not_found -> failwith "No ``Host:'' header in request" in
101          let hostname = String.lowercase hostname in
102
103          let sth =
104            dbh#prepare_cached
105              "select h.id, h.canonical_hostname, h.edit_anon
106                 from hostnames hn, hosts h
107                where hn.name = ? and hn.hostid = h.id" in
108          sth#execute [`String hostname];
109
110          try
111            (match sth#fetch1 () with
112                 [ `Int id; `String hostname; `Bool edit_anon ] ->
113                   id, hostname, edit_anon
114               | _ -> assert false)
115          with
116              Not_found ->
117                failwith ("Hostname ``" ^ hostname ^ "'' not found in " ^
118                          "the hosts/hostnames tables in the database.") in
119
120        (* Create the host object. *)
121        let host = { hostname = hostname; edit_anon = edit_anon; } in
122
123        (* Look for the user's cookie, and determine from this the user
124         * object.
125         *)
126        let user =
127          try
128            let cookie =
129              (* Allow the user to deliberately specify an extra "cookie"
130               * parameter, which we will send back as a cookie.  This is
131               * useful for "mail my password"-type scripts.
132               *)
133              if q#param_exists "cookie" then (
134                let value = q#param "cookie" in
135                let cookie = Cookie.cookie ~name:"auth" ~value ~path:"/" () in
136                Table.set (Request.headers_out r) "Set-Cookie" cookie#as_string;
137                value
138              ) else (
139                (* Normal cookie, from the headers. *)
140                let header = Table.get (Request.headers_in r) "Cookie" in
141                let cookies = Cookie.parse header in
142                let cookie =
143                  List.find (fun cookie -> cookie#name = "auth") cookies in
144                cookie#value
145              ) in
146
147            let sth =
148              dbh#prepare_cached
149                "select u.id, u.name, u.can_edit, u.can_manage_users,
150                        u.can_manage_contacts
151                   from usercookies uc, users u
152                  where uc.cookie = ? and uc.userid = u.id and u.hostid = ?" in
153            sth#execute [`String cookie; `Int hostid];
154            (match sth#fetch1 () with
155                 [ `Int userid; `String name;
156                   `Bool can_edit; `Bool can_manage_users;
157                   `Bool can_manage_contacts ] ->
158                   let perms =
159                     (if can_edit then [ CanEdit ] else []) @
160                     (if can_manage_users then [ CanManageUsers ] else []) @
161                     (if can_manage_contacts then [ CanManageContacts ] else [])
162                   in
163                   User (userid, name, perms)
164               | _ -> assert false)
165          with
166              Not_found -> Anonymous
167        in
168
169        (* If the ~restrict parameter is given, then we want to check that
170         * the user has sufficient permission to run this script.
171         *)
172        let permitted =
173          if not anonymous && user = Anonymous then false
174          else
175            match restrict with
176                [] -> true               (* empty list = no restrictions *)
177              | rs ->
178                  List.fold_left ((||)) false
179                    (List.map (fun r -> test_permission edit_anon r user) rs) in
180
181        if permitted then (
182          (* Call the actual CGI script. *)
183          try
184            run r q dbh hostid host user
185          with
186              CgiExit -> ()
187        ) else
188          error ~back_button:true
189            ~title:"Access denied"
190            q "You do not have permission to access this part of the site."
191     )
192
193 (* Convert a section name into something valid for use in <a name="...">
194  * XXX This breaks horribly for non-7-bit strings.
195  * XXX This is stuck here because we don't have a good place for it, and
196  * because it needs to be fixed for i18n compliance.
197  *)
198 let linkname_of_sectionname str =
199   let str = String.copy str in
200   for i = 0 to String.length str - 1 do
201     if not (isalnum str.[i]) then str.[i] <- '_'
202   done;
203   str