Fixed up to work with mod_caml 1.3.0-2.
[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.22 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 ExtString
28
29 open Cocanwiki
30 open Cocanwiki_template
31 open Cocanwiki_ok
32 open Cocanwiki_date
33 open Cocanwiki_server_settings
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 (* Referer strings which help us decide if the user came from
43  * a search engine and highlight terms in the page appropriately.
44  *)
45 let search_engines = [
46   Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
47   Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
48   Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
49 ]
50 let split_words = Pcre.regexp "\\W+"
51
52 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
53
54 let run r (q : cgi) (dbh : Dbi.connection) hostid {edit_anon=edit_anon} user =
55   let template_page = get_template dbh hostid "page.html" in
56   let template_404  = get_template dbh hostid "page_404.html" in
57
58   let page = q#param "page" in
59   let page = if page = "" then "index" else page in
60
61   (* Host-specific fields. *)
62   let sth = dbh#prepare_cached "select css is not null,
63                                        feedback_email is not null,
64                                        mailing_list
65                                   from hosts where id = ?" in
66   sth#execute [`Int hostid];
67   let has_host_css, has_feedback_email, mailing_list =
68     match sth#fetch1 () with
69       | [ `Bool has_host_css; `Bool has_feedback_email; `Bool mailing_list ] ->
70           has_host_css, has_feedback_email, mailing_list
71       | _ -> assert false in
72
73   (* Can the user edit?  Manage users?  etc. *)
74   let can_edit = can_edit edit_anon user in
75   let can_manage_users = can_manage_users user in
76   let can_manage_contacts = can_manage_contacts user in
77   let can_manage_site = can_manage_site user in
78   let can_edit_global_css = can_edit_global_css user in
79
80   (* Do we have a stats page set up? *)
81   let has_stats = server_settings_stats_page dbh <> None in
82
83   (* Given the referer string, return the list of search terms.  If none
84    * can be found, then throws Not_found.
85    *)
86   let search_terms_from_referer referer =
87     let _, argnames =
88       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
89     let args = Cgi_args.parse referer in
90     let argname =
91       List.find (fun argname -> List.mem_assoc argname args) argnames in
92     let search_string = List.assoc argname args in
93     Pcre.split ~rex:split_words search_string
94   in
95
96   (* Given a full page of XHTML, highlight search terms found in the
97    * <body> part of the page.
98    *)
99   let highlight_search_terms xhtml search_terms span_class =
100     (* Split the original XHTML into strings and tags.  For example if
101      * the original string is: "This is some <b>bold</b> text.<br/>", then
102      * after this step we will have the following list:
103      * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
104      *)
105     let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
106     let xhtml = Array.to_list xhtml in
107     let xhtml = List.map (fun matches -> matches.(0)) xhtml in
108
109     (* Find the <body> ... </body> tags.  We only want to apply
110      * highlighting to tags within this area.
111      *)
112     let rec list_split f acc = function
113       | [] -> List.rev acc, []
114       | ((x :: _) as xs) when f x -> List.rev acc, xs
115       | x :: xs ->
116           let acc = x :: acc in
117           list_split f acc xs
118     in
119     let head, body =
120       list_split (fun str -> String.starts_with str "<body") [] xhtml in
121     let body, tail =
122       list_split ((=) "</body>") [] body in
123     (* NB: Hopefully, xhtml = head @ body @ tail. *)
124
125     (* The search terms are a list of simple words.  Turn into a big
126      * regular expression, because we want to substitute for each.  We
127      * end up with a regexp like '(word1|word2|word3)'.
128      *)
129     let rex =
130       Pcre.regexp ~flags:[`CASELESS]
131         ("(" ^ String.concat "|" search_terms ^ ")") in
132
133     (* Do the substitution, but only on text, not elements! *)
134     let body =
135       let subst text =
136         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
137       in
138       List.map (fun str ->
139                   if String.length str > 0 && str.[0] != '<' then
140                     Pcre.substitute ~rex ~subst str
141                   else
142                     str) body in
143
144     (* Join the XHTML fragments back together again. *)
145     String.concat "" (List.concat [ head ; body ; tail ])
146   in
147
148   (* This code generates ordinary pages. *)
149   let make_page title description pageid last_modified_date has_page_css
150       version page page' =
151     let t = template_page in
152     t#set "title" title;
153     t#set "description" description;
154     t#set "pageid" (string_of_int pageid);
155     t#set "last_modified_date" (printable_date last_modified_date);
156
157     if page <> page' then (* redirection *) (
158       t#set "page" page';
159       t#set "original_page" page; (* XXX title - get it from database *)
160       t#conditional "redirected" true
161     ) else (
162       t#set "page" page;
163       t#conditional "redirected" false
164     );
165
166     t#conditional "has_host_css" has_host_css;
167     t#conditional "has_page_css" has_page_css;
168
169     t#conditional "has_feedback_email" has_feedback_email;
170     t#conditional "mailing_list" mailing_list;
171
172     t#conditional "can_edit" can_edit;
173     t#conditional "can_manage_users" can_manage_users;
174     t#conditional "can_manage_contacts" can_manage_contacts;
175     t#conditional "can_manage_site" can_manage_site;
176     t#conditional "can_edit_global_css" can_edit_global_css;
177
178     t#conditional "has_stats" has_stats;
179
180     (* Pull out the sections in this page. *)
181     let sth = dbh#prepare_cached
182                 "select ordering, sectionname, content, divname
183                    from contents
184                   where pageid = ?
185                   order by ordering" in
186     sth#execute [`Int pageid];
187
188     let sections =
189       sth#map
190         (function [`Int ordering;
191                    (`Null | `String _) as sectionname;
192                    `String content;
193                    (`Null | `String _) as divname] ->
194            let divname, has_divname =
195              match divname with
196                  `Null -> "", false
197                | `String divname -> divname, true in
198            let sectionname, has_sectionname =
199              match sectionname with
200                  `Null -> "", false
201                | `String sectionname -> sectionname, true in
202            let linkname = linkname_of_sectionname sectionname in
203            [ "ordering", Template.VarString (string_of_int ordering);
204              "has_sectionname", Template.VarConditional has_sectionname;
205              "sectionname", Template.VarString sectionname;
206              "linkname", Template.VarString linkname;
207              "content",
208                Template.VarString
209                  (Wikilib.xhtml_of_content dbh hostid content);
210              "has_divname", Template.VarConditional has_divname;
211              "divname", Template.VarString divname ]
212            | _ -> assert false) in
213
214     t#table "sections" sections;
215
216     (* Are we showing an old version of the page?  If so, warn. *)
217     (match version with
218          None ->
219            t#conditional "is_old_version" false
220        | Some pageid ->
221            t#conditional "is_old_version" true;
222            t#set "old_version" (string_of_int pageid));
223
224     (* Login status. *)
225     (match user with
226          Anonymous ->
227            t#conditional "user_logged_in" false
228        | User (_, username, _) ->
229            t#conditional "user_logged_in" true;
230            t#set "username" username);
231
232     (* If we are coming from a search engine then we want to highlight
233      * search terms throughout the whole page ...
234      *)
235     try
236       let referer = Table.get (Request.headers_in r) "Referer" in
237       let search_terms = search_terms_from_referer referer in
238
239       (* Highlight the search terms. *)
240       let xhtml = t#to_string in
241       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
242
243       (* Deliver the page. *)
244       q#header ();
245       print_string r xhtml
246     with
247         Not_found ->
248           (* No referer / no search terms / not a search engine referer. *)
249           q#template t
250   in
251
252   (* This code generates 404 pages. *)
253   let make_404 () =
254     Request.set_status r 404;           (* Return a 404 error code. *)
255
256     let t = template_404 in
257     t#set "page" page;
258
259     let search_terms =
260       String.map
261         (function
262              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
263            | _ -> ' ') page in
264
265     t#set "search_terms" search_terms;
266
267     t#conditional "has_host_css" has_host_css;
268
269     t#conditional "can_edit" can_edit;
270     t#conditional "can_manage_users" can_manage_users;
271     t#conditional "can_manage_contacts" can_manage_contacts;
272     t#conditional "can_manage_site" can_manage_site;
273     t#conditional "can_edit_global_css" can_edit_global_css;
274
275     t#conditional "has_stats" has_stats;
276
277     q#template t
278   in
279
280   (* Fetch a page by name.  This function can give three answers:
281    * (1) Page fetched OK (fetches some details of the page).
282    * (2) Page is a redirect (fetches the name of the redirect page).
283    * (3) Page not found in database, ie. 404 error.
284    *)
285   (* XXX Should do a case-insensitive matching of URLs, and if the URL differs
286    * in case only should redirect to the lowercase version.
287    *)
288   let fetch_page page version allow_redirect =
289     match version with
290       | None ->
291           if allow_redirect then (
292             let sth =
293               dbh#prepare_cached
294                 "select redirect, id, title, description, last_modified_date,
295                         css is not null
296                    from pages where hostid = ? and url = ?" in
297             sth#execute [`Int hostid; `String page];
298             (try
299                (match sth#fetch1 () with
300                   | [ `Null; `Int id; `String title; `String description;
301                       `Timestamp last_modified_date; `Bool has_page_css ] ->
302                       FPOK (id, title, description, last_modified_date,
303                             has_page_css)
304                   | `String redirect :: _ ->
305                       FPRedirect redirect
306                   | _ -> assert false)
307              with
308                  Not_found -> FPNotFound)
309           ) else (* redirects not allowed ... *) (
310             let sth =
311               dbh#prepare_cached
312                 "select id, title, description, last_modified_date,
313                         css is not null
314                    from pages where hostid = ? and url = ?" in
315             sth#execute [`Int hostid; `String page];
316             (try
317                (match sth#fetch1 () with
318                   | [ `Int id; `String title; `String description;
319                       `Timestamp last_modified_date; `Bool has_page_css ] ->
320                       FPOK (id, title, description, last_modified_date,
321                             has_page_css)
322                   | _ -> assert false)
323              with
324                  Not_found -> FPNotFound)
325           )
326       | Some version ->
327             let sth =
328               dbh#prepare_cached
329                 "select id, title, description, last_modified_date,
330                         css is not null
331                    from pages
332                   where hostid = ? and id = ? and
333                         (url = ? or url_deleted = ?)" in
334             sth#execute [`Int hostid; `Int version;
335                          `String page; `String page];
336             (try
337                (match sth#fetch1 () with
338                   | [ `Int id; `String title; `String description;
339                       `Timestamp last_modified_date; `Bool has_page_css ] ->
340                       FPOK (id, title, description, last_modified_date,
341                             has_page_css)
342                   | _ -> assert false)
343              with
344                  Not_found -> FPNotFound)
345   in
346
347   (* Here we deal with the complex business of redirects and versions. *)
348   (* Only allow the no_redirect and version syntax for editors. *)
349   let allow_redirect, version =
350     if can_edit then (
351       not (q#param_true "no_redirect"),
352       try Some (int_of_string (q#param "version")) with Not_found -> None
353     ) else
354       (true, None) in
355
356   let rec loop page' i =
357     if i > max_redirect then (
358       error ~title:"Too many redirections" ~back_button:true
359         q ("Too many redirects between pages.  This may happen because " ^
360            "of a cycle of redirections.");
361       return ()
362     ) else
363       match fetch_page page' version allow_redirect with
364         | FPOK (pageid, title, description, last_modified_date, has_page_css)->
365             make_page title description pageid last_modified_date has_page_css
366               version page page'
367         | FPRedirect page' ->
368             loop page' (i+1)
369         | FPNotFound ->
370             make_404 ()
371   in
372   loop page 0
373
374 let () =
375   register_script run