Command-line tools for importing mail (uses 'curl').
[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.17 2004/10/11 14:13:04 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                 edit_anon : bool;
40                 view_anon : bool }
41
42 (* Permissions and restrictions.
43  *
44  * Use the optional ~restrict parameter to register_script to restrict
45  * who can use the script.  For example:
46  *   register_script ~restrict:[CanEdit ; CanManageUsers] run
47  *)
48 type permissions_t = CanView | CanEdit | CanManageUsers | CanManageContacts
49                    | CanManageSite | CanEditGlobalCSS | CanImportMail
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 = edit_anon; view_anon = view_anon} perm user =
57   if perm = CanEdit && edit_anon then true
58   else if perm = CanView && view_anon then true
59   else match user with
60       Anonymous -> false
61     | User (_, _, perms) -> List.mem perm perms
62
63 let can_edit host = test_permission host CanEdit
64 let can_manage_users host = test_permission host CanManageUsers
65 let can_manage_contacts host = test_permission host CanManageContacts
66 let can_manage_site host = test_permission host CanManageSite
67 let can_edit_global_css host = test_permission host CanEditGlobalCSS
68 let can_import_mail host = test_permission host CanImportMail
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, view_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, h.view_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;
113                   `Bool edit_anon; `Bool view_anon ] ->
114                   id, hostname, edit_anon, view_anon
115               | _ -> assert false)
116          with
117              Not_found ->
118                failwith ("Hostname ``" ^ hostname ^ "'' not found in " ^
119                          "the hosts/hostnames tables in the database.") in
120
121        (* Create the host object. *)
122        let host = { hostname = hostname;
123                     edit_anon = edit_anon;
124                     view_anon = view_anon } in
125
126        (* Look for the user's cookie, and determine from this the user
127         * object.
128         *)
129        let user =
130          try
131            let cookie =
132              (* Allow the user to deliberately specify an extra "cookie"
133               * parameter, which we will send back as a cookie.  This is
134               * useful for "mail my password"-type scripts.
135               *)
136              if q#param_exists "cookie" then (
137                let value = q#param "cookie" in
138                let cookie = Cookie.cookie ~name:"auth" ~value ~path:"/" () in
139                Table.set (Request.headers_out r) "Set-Cookie" cookie#as_string;
140                value
141              ) else (
142                (* Normal cookie, from the headers. *)
143                let header = Table.get (Request.headers_in r) "Cookie" in
144                let cookies = Cookie.parse header in
145                let cookie =
146                  List.find (fun cookie -> cookie#name = "auth") cookies in
147                cookie#value
148              ) in
149
150            let sth =
151              dbh#prepare_cached
152                "select u.id, u.name, u.can_edit, u.can_manage_users,
153                        u.can_manage_contacts, u.can_manage_site,
154                        u.can_edit_global_css, u.can_import_mail
155                   from usercookies uc, users u
156                  where uc.cookie = ? and uc.userid = u.id and u.hostid = ?" in
157            sth#execute [`String cookie; `Int hostid];
158            (match sth#fetch1 () with
159                 [ `Int userid; `String name;
160                   `Bool can_edit; `Bool can_manage_users;
161                   `Bool can_manage_contacts; `Bool can_manage_site;
162                   `Bool can_edit_global_css; `Bool can_import_mail ] ->
163                   (* Every logged in user can view. *)
164                   let perms = [CanView] in
165                   let perms =
166                     if can_edit then CanEdit :: perms
167                     else perms in
168                   let perms =
169                     if can_manage_users then CanManageUsers :: perms
170                     else perms in
171                   let perms =
172                     if can_manage_contacts then CanManageContacts :: perms
173                     else perms in
174                   let perms =
175                     if can_manage_site then CanManageSite :: perms
176                     else perms in
177                   let perms =
178                     if can_edit_global_css then CanEditGlobalCSS :: perms
179                     else perms in
180                   let perms =
181                     if can_import_mail then CanImportMail :: perms
182                     else perms in
183                   User (userid, name, perms)
184               | _ -> assert false)
185          with
186              Not_found -> Anonymous
187        in
188
189        (* If the ~restrict parameter is given, then we want to check that
190         * the user has sufficient permission to run this script.
191         *)
192        let permitted =
193          if not anonymous && user = Anonymous then false
194          else
195            match restrict with
196                [] -> true               (* empty list = no restrictions *)
197              | rs ->
198                  List.fold_left (||) false
199                    (List.map (fun r -> test_permission host r user) rs) in
200
201        if permitted then (
202          (* Call the actual CGI script. *)
203          run r q dbh hostid host user
204        ) else (
205          if user = Anonymous then
206            q#redirect ("http://" ^ hostname ^ "/_login")
207          else
208            error ~back_button:true
209              ~title:"Access denied"
210              q "You do not have permission to access this part of the site."
211        )
212     )
213
214 (* Convert a section name into something valid for use in <a name="...">
215  * XXX This breaks horribly for non-7-bit strings.
216  * XXX This is stuck here because we don't have a good place for it, and
217  * because it needs to be fixed for i18n compliance.
218  *)
219 let linkname_of_sectionname str =
220   let str = String.copy str in
221   for i = 0 to String.length str - 1 do
222     if not (isalnum str.[i]) then str.[i] <- '_'
223   done;
224   str
225
226 (* List of extensions currently registered. *)
227 type extension_t = Dbi.connection -> int -> string -> string
228 let extensions = ref ([] : (string * extension_t) list)
229
230 (* Maximum degree of redirection. *)
231 let max_redirect = 4