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