366d34e759a6d7dbd33eabeebc1669e21b0ca177
[cocanwiki.git] / scripts / page.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: page.ml,v 1.14 2004/09/20 11:11:15 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 ExtString
28
29 open Cocanwiki
30 open Cocanwiki_template
31 open Cocanwiki_ok
32 open Cocanwiki_date
33 open Cocanwiki_strings
34
35 (* Maximum level of redirection. *)
36 let max_redirect = 4
37
38 type fp_status = FPOK of int * string * string * Dbi.datetime * bool
39                | FPRedirect of string
40                | FPNotFound
41
42 let run r (q : cgi) (dbh : Dbi.connection) hostid {edit_anon=edit_anon} user =
43   let template_page = get_template dbh hostid "page.html" in
44   let template_404  = get_template dbh hostid "page_404.html" in
45
46   let page = q#param "page" in
47   let page = if page = "" then "index" else page in
48
49   (* Host-specific CSS? *)
50   let sth = dbh#prepare_cached "select css is not null from hosts
51                                  where id = ?" in
52   sth#execute [`Int hostid];
53   let has_host_css =
54     match sth#fetch1 () with
55       | [ `Bool has_host_css ] -> has_host_css
56       | _ -> assert false in
57
58   (* Can the user edit?  Manage users?  etc. *)
59   let can_edit = can_edit edit_anon user in
60   let can_manage_users = can_manage_users user in
61   let can_manage_contacts = can_manage_contacts user in
62
63   (* Convert a section name into something valid for use in <a name="...">
64    * XXX This breaks horribly for non-7-bit strings.
65    *)
66   let linkname_of_sectionname str =
67     let str = String.copy str in
68     for i = 0 to String.length str - 1 do
69       if not (isalnum str.[i]) then str.[i] <- '_'
70     done;
71     str
72   in
73
74   (* This code generates ordinary pages. *)
75   let make_page title description pageid last_modified_date has_page_css
76       version page page' =
77     let t = template_page in
78     t#set "title" title;
79     t#set "description" description;
80     t#set "pageid" (string_of_int pageid);
81     t#set "last_modified_date" (printable_date last_modified_date);
82
83     if page <> page' then (* redirection *) (
84       t#set "page" page';
85       t#set "original_page" page; (* XXX title - get it from database *)
86       t#conditional "redirected" true
87     ) else (
88       t#set "page" page;
89       t#conditional "redirected" false
90     );
91
92     t#conditional "has_host_css" has_host_css;
93     t#conditional "has_page_css" has_page_css;
94
95     t#conditional "can_edit" can_edit;
96     t#conditional "can_manage_users" can_manage_users;
97     t#conditional "can_manage_contacts" can_manage_contacts;
98
99     (* Pull out the sections in this page. *)
100     let sth = dbh#prepare_cached
101                 "select ordering, sectionname, content, divname
102                    from contents
103                   where pageid = ?
104                   order by ordering" in
105     sth#execute [`Int pageid];
106
107     let sections =
108       sth#map
109         (function [`Int ordering;
110                    (`Null | `String _) as sectionname;
111                    `String content;
112                    (`Null | `String _) as divname] ->
113            let divname, has_divname =
114              match divname with
115                  `Null -> "", false
116                | `String divname -> divname, true in
117            let sectionname, has_sectionname =
118              match sectionname with
119                  `Null -> "", false
120                | `String sectionname -> sectionname, true in
121            let linkname = linkname_of_sectionname sectionname in
122            [ "ordering", Template.VarString (string_of_int ordering);
123              "has_sectionname", Template.VarConditional has_sectionname;
124              "sectionname", Template.VarString sectionname;
125              "linkname", Template.VarString linkname;
126              "content",
127                Template.VarString
128                  (Wikilib.xhtml_of_content dbh hostid content);
129              "has_divname", Template.VarConditional has_divname;
130              "divname", Template.VarString divname ]
131            | _ -> assert false) in
132
133     t#table "sections" sections;
134
135     (* Are we showing an old version of the page?  If so, warn. *)
136     (match version with
137          None ->
138            t#conditional "is_old_version" false
139        | Some pageid ->
140            t#conditional "is_old_version" true;
141            t#set "old_version" (string_of_int pageid));
142
143     (* Login status. *)
144     (match user with
145          Anonymous ->
146            t#conditional "user_logged_in" false
147        | User (_, username, _) ->
148            t#conditional "user_logged_in" true;
149            t#set "username" username);
150
151     q#template t
152   in
153
154   (* This code generates 404 pages. *)
155   let make_404 () =
156     Request.set_status r 404;           (* Return a 404 error code. *)
157
158     let t = template_404 in
159     t#set "page" page;
160
161     let search_terms =
162       String.map
163         (function
164              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
165            | _ -> ' ') page in
166
167     t#set "search_terms" search_terms;
168
169     t#conditional "has_host_css" has_host_css;
170
171     t#conditional "can_edit" can_edit;
172     t#conditional "can_manage_users" can_manage_users;
173     t#conditional "can_manage_contacts" can_manage_contacts;
174
175     q#template t
176   in
177
178   (* Fetch a page by name.  This function can give three answers:
179    * (1) Page fetched OK (fetches some details of the page).
180    * (2) Page is a redirect (fetches the name of the redirect page).
181    * (3) Page not found in database, ie. 404 error.
182    *)
183   (* XXX Should do a case-insensitive matching of URLs, and if the URL differs
184    * in case only should redirect to the lowercase version.
185    *)
186   let fetch_page page version allow_redirect =
187     match version with
188       | None ->
189           if allow_redirect then (
190             let sth =
191               dbh#prepare_cached
192                 "select redirect, id, title, description, last_modified_date,
193                         css is not null
194                    from pages where hostid = ? and url = ?" in
195             sth#execute [`Int hostid; `String page];
196             (try
197                (match sth#fetch1 () with
198                   | [ `Null; `Int id; `String title; `String description;
199                       `Timestamp last_modified_date; `Bool has_page_css ] ->
200                       FPOK (id, title, description, last_modified_date,
201                             has_page_css)
202                   | `String redirect :: _ ->
203                       FPRedirect redirect
204                   | _ -> assert false)
205              with
206                  Not_found -> FPNotFound)
207           ) else (* redirects not allowed ... *) (
208             let sth =
209               dbh#prepare_cached
210                 "select id, title, description, last_modified_date,
211                         css is not null
212                    from pages where hostid = ? and url = ?" in
213             sth#execute [`Int hostid; `String page];
214             (try
215                (match sth#fetch1 () with
216                   | [ `Int id; `String title; `String description;
217                       `Timestamp last_modified_date; `Bool has_page_css ] ->
218                       FPOK (id, title, description, last_modified_date,
219                             has_page_css)
220                   | _ -> assert false)
221              with
222                  Not_found -> FPNotFound)
223           )
224       | Some version ->
225             let sth =
226               dbh#prepare_cached
227                 "select id, title, description, last_modified_date,
228                         css is not null
229                    from pages
230                   where hostid = ? and id = ? and
231                         (url = ? or url_deleted = ?)" in
232             sth#execute [`Int hostid; `Int version;
233                          `String page; `String page];
234             (try
235                (match sth#fetch1 () with
236                   | [ `Int id; `String title; `String description;
237                       `Timestamp last_modified_date; `Bool has_page_css ] ->
238                       FPOK (id, title, description, last_modified_date,
239                             has_page_css)
240                   | _ -> assert false)
241              with
242                  Not_found -> FPNotFound)
243   in
244
245   (* Here we deal with the complex business of redirects and versions. *)
246   (* Only allow the no_redirect and version syntax for editors. *)
247   let allow_redirect, version =
248     if can_edit then (
249       not (q#param_true "no_redirect"),
250       try Some (int_of_string (q#param "version")) with Not_found -> None
251     ) else
252       (true, None) in
253
254   let rec loop page' i =
255     if i > max_redirect then (
256       error ~title:"Too many redirections" ~back_button:true
257         q ("Too many redirects between pages.  This may happen because " ^
258            "of a cycle of redirections.");
259       raise CgiExit
260     ) else
261       match fetch_page page' version allow_redirect with
262         | FPOK (pageid, title, description, last_modified_date, has_page_css)->
263             make_page title description pageid last_modified_date has_page_css
264               version page page'
265         | FPRedirect page' ->
266             loop page' (i+1)
267         | FPNotFound ->
268             make_404 ()
269   in
270   loop page 0
271
272 let () =
273   register_script run