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