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