More thorough inclusion of the page bug. This should mean the page bug appears just...
[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.42 2005/11/24 14:54:12 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 open ExtList
29
30 open Cocanwiki
31 open Cocanwiki_template
32 open Cocanwiki_ok
33 open Cocanwiki_date
34 open Cocanwiki_server_settings
35 open Cocanwiki_links
36
37 type fp_status = FPOK of int * string * string * Dbi.datetime * bool
38                | FPInternalRedirect of string
39                | FPExternalRedirect 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 split_qs_re = Pcre.regexp "\\?"
53
54 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
55
56 let run r (q : cgi) (dbh : Dbi.connection) hostid
57     ({ edit_anon = edit_anon; view_anon = view_anon } as host)
58     user =
59   let page = q#param "page" in
60   let page = if page = "" then "index" else page in
61
62   (* The main "page" template is split in two to improve the speed of
63    * delivery of the page.  The very first part ("page_header.html")
64    * contains the page <head>, crucially including all the links to the
65    * stylesheets.  We send this first and flush it out to the client so
66    * that the client can begin requesting stylesheets, background images
67    * and so on.  After this we compose the main page ("page.html") and
68    * send it out second.
69    *)
70
71   let template_page_header =
72     get_template ~page dbh hostid "page_header.html" in
73   let template_page = get_template ~page dbh hostid "page.html" in
74
75   (* This is the simpler template for 404 pages. *)
76   let template_404  = get_template dbh hostid "page_404.html" in
77
78   (* Host-specific fields. *)
79   let sth = dbh#prepare_cached "select css is not null,
80                                        feedback_email is not null,
81                                        mailing_list, navigation
82                                   from hosts where id = ?" in
83   sth#execute [`Int hostid];
84   let has_host_css, has_feedback_email, mailing_list, navigation =
85     match sth#fetch1 () with
86       | [ `Bool has_host_css; `Bool has_feedback_email; `Bool mailing_list;
87           `Bool navigation ] ->
88           has_host_css, has_feedback_email, mailing_list, navigation
89       | _ -> assert false in
90
91   (* User permissions. *)
92   let can_edit = can_edit host user in
93   let can_manage_users = can_manage_users host user in
94
95   (* Do we have a stats page set up? *)
96   let has_stats = server_settings_stats_page dbh <> None in
97
98   (* Given the referer string, return the list of search terms.  If none
99    * can be found, then throws Not_found.
100    *)
101   let search_terms_from_referer referer =
102     let _, argnames =
103       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
104     let url, qs =
105       match Pcre.split ~rex:split_qs_re ~max:2 referer with
106         | [url] | [url;""] -> url, ""
107         | [url;qs] -> url, qs
108         | _ -> assert false in
109     let args = Cgi_args.parse qs in
110     let argname =
111       List.find (fun argname -> List.mem_assoc argname args) argnames in
112     let search_string = List.assoc argname args in
113     Pcre.split ~rex:split_words search_string
114   in
115
116   (* Given a full page of XHTML, highlight search terms found in the
117    * <body> part of the page.
118    *)
119   let highlight_search_terms xhtml search_terms span_class =
120     (* Split the original XHTML into strings and tags.  For example if
121      * the original string is: "This is some <b>bold</b> text.<br/>", then
122      * after this step we will have the following list:
123      * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
124      *)
125     let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
126     let xhtml = Array.to_list xhtml in
127     let xhtml = List.map (fun matches -> matches.(0)) xhtml in
128
129     (* Find the <body> ... </body> tags.  We only want to apply
130      * highlighting to tags within this area.
131      *)
132     let rec list_split f acc = function
133       | [] -> List.rev acc, []
134       | ((x :: _) as xs) when f x -> List.rev acc, xs
135       | x :: xs ->
136           let acc = x :: acc in
137           list_split f acc xs
138     in
139     let head, body =
140       list_split (fun str -> String.starts_with str "<body") [] xhtml in
141     let body, tail =
142       list_split ((=) "</body>") [] body in
143     (* NB: Hopefully, xhtml = head @ body @ tail. *)
144
145     (* The search terms are a list of simple words.  Turn into a big
146      * regular expression, because we want to substitute for each.  We
147      * end up with a regexp like '(word1|word2|word3)'.
148      *)
149     let rex =
150       Pcre.regexp ~flags:[`CASELESS]
151         ("(" ^ String.concat "|" search_terms ^ ")") in
152
153     (* Do the substitution, but only on text, not elements! *)
154     let body =
155       let subst text =
156         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
157       in
158       List.map (fun str ->
159                   if String.length str > 0 && str.[0] != '<' then
160                     Pcre.substitute ~rex ~subst str
161                   else
162                     str) body in
163
164     (* Join the XHTML fragments back together again. *)
165     String.concat "" (List.concat [ head ; body ; tail ])
166   in
167
168   (* Check the templates table for extensions. *)
169   let get_extension url =
170     let sth = dbh#prepare_cached "select extension from templates
171                                    where ? ~ url_regexp
172                                    order by ordering
173                                    limit 1" in
174     sth#execute [`String url];
175
176     try
177       let name = sth#fetch1string () in
178       Some (List.assoc name !extensions)
179     with
180         Not_found -> None
181   in
182
183   (* This code generates ordinary pages. *)
184   let make_page title description pageid last_modified_date has_page_css
185       version page page' extension =
186     let t = template_page in
187     let th = template_page_header in
188     t#set "title" title;
189     th#set "title" title;
190     t#set "last_modified_date" last_modified_date;
191
192     (match description with
193          None -> th#conditional "has_description" false
194        | Some description ->
195            th#conditional "has_description" true;
196            th#set "description" description);
197
198     if page <> page' then (* redirection *) (
199       t#set "page" page';
200       th#set "page" page';
201       t#set "original_page" page; (* XXX title - get it from database *)
202       t#conditional "redirected" true
203     ) else (
204       t#set "page" page;
205       th#set "page" page;
206       t#conditional "redirected" false
207     );
208
209     th#conditional "has_host_css" has_host_css;
210     th#conditional "has_page_css" has_page_css;
211
212     (* Are we showing an old version of the page?  If so, warn. *)
213     (match version with
214          None ->
215            t#conditional "is_old_version" false;
216            th#conditional "is_old_version" false
217        | Some pageid ->
218            t#conditional "is_old_version" true;
219            th#conditional "is_old_version" true;
220            t#set "old_version" (string_of_int pageid);
221            th#set "old_version" (string_of_int pageid));
222
223     (* At this point, we can print out the header and flush it back to
224      * the user, allowing the browser to start fetching stylesheets
225      * and background images while we compose the page.
226      *)
227     q#header ();
228     print_string r th#to_string;
229     Request.rflush r;
230
231     t#conditional "has_feedback_email" has_feedback_email;
232     t#conditional "mailing_list" mailing_list;
233     t#conditional "navigation" navigation;
234
235     t#conditional "can_edit" can_edit;
236     t#conditional "can_manage_users" can_manage_users;
237     t#conditional "has_stats" has_stats;
238
239     (* Pull out the sections in this page. *)
240     let sections =
241       match pageid with
242           None -> []
243         | Some pageid ->
244             let sth = dbh#prepare_cached
245                         "select ordering, sectionname, content, divname
246                            from contents where pageid = ? order by ordering" in
247             sth#execute [`Int pageid];
248
249             sth#map
250               (function [`Int ordering;
251                          (`Null | `String _) as sectionname;
252                          `String content;
253                          (`Null | `String _) as divname] ->
254                  let divname, has_divname =
255                    match divname with
256                        `Null -> "", false
257                      | `String divname -> divname, true in
258                  let sectionname, has_sectionname =
259                    match sectionname with
260                        `Null -> "", false
261                      | `String sectionname -> sectionname, true in
262                  let linkname = linkname_of_sectionname sectionname in
263                  [ "ordering", Template.VarString (string_of_int ordering);
264                    "has_sectionname",
265                      Template.VarConditional has_sectionname;
266                    "sectionname", Template.VarString sectionname;
267                    "linkname", Template.VarString linkname;
268                    "content",
269                      Template.VarString
270                        (Wikilib.xhtml_of_content dbh hostid content);
271                    "has_divname", Template.VarConditional has_divname;
272                    "divname", Template.VarString divname ]
273                  | _ -> assert false) in
274
275     (* Call an extension to generate the first section in this page? *)
276     let sections =
277       match extension with
278           None -> sections
279         | Some extension ->
280             let content = extension dbh hostid page' in
281             let section = [
282               "ordering", Template.VarString "0";
283               "has_sectionname", Template.VarConditional false;
284               "linkname", Template.VarString "";
285               "content", Template.VarString content;
286               "has_divname", Template.VarConditional true;
287               "divname", Template.VarString "form_div";
288             ] in
289             section :: sections in
290
291     t#table "sections" sections;
292
293     (* Login status. *)
294     (match user with
295          Anonymous ->
296            t#conditional "user_logged_in" false
297        | User (_, username, _, _) ->
298            t#conditional "user_logged_in" true;
299            t#set "username" username);
300
301     (* If logged in, we want to update the recently_visited table. *)
302     if pageid <> None then (
303       match user with
304         | User (userid, _, _, _) ->
305             let sth = dbh#prepare_cached "delete from recently_visited
306                                            where hostid = ? and userid = ?
307                                              and url = ?" in
308             sth#execute [`Int hostid; `Int userid; `String page'];
309             let sth = dbh#prepare_cached
310                         "insert into recently_visited (hostid, userid, url)
311                          values (?, ?, ?)" in
312             sth#execute [`Int hostid; `Int userid; `String page'];
313             dbh#commit ()
314         | _ -> ()
315     );
316
317     (* Navigation links. *)
318     if navigation then (
319       let max_links = 18 in             (* Show no more links than this. *)
320
321       (* What links here. *)
322       let wlh = what_links_here dbh hostid page' in
323       let wlh = List.take max_links wlh in
324       let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
325
326       let rv =
327         match user with
328           | User (userid, _, _, _) ->
329               (* Recently visited URLs, but don't repeat any from the 'what
330                * links here' section, and don't link to self.
331                *)
332               let not_urls = page' :: wlh_urls in
333               let limit = max_links - List.length wlh_urls in
334               let qs = Dbi.placeholders (List.length not_urls) in
335               let sth =
336                 dbh#prepare_cached
337                   ("select rv.url, p.title, rv.visit_time
338                       from recently_visited rv, pages p
339                      where rv.hostid = ? and rv.userid = ?
340                        and rv.url not in " ^ qs ^ "
341                        and rv.hostid = p.hostid and rv.url = p.url
342                      order by 3 desc
343                      limit ?") in
344               let args = List.map (fun s -> `String s) not_urls in
345               sth#execute
346                 ([`Int hostid; `Int userid] @ args @ [`Int limit]);
347               sth#map
348                 (function [`String url; `String title; _] ->
349                    url, title
350                    | _ -> assert false)
351           | _ -> [] in
352
353       (* Links to page. *)
354       let f (page, title) = [ "page", Template.VarString page;
355                               "title", Template.VarString title ] in
356       let table = List.map f wlh in
357       t#table "what_links_here" table;
358       t#conditional "has_what_links_here" (wlh <> []);
359
360       let table = List.map f rv in
361       t#table "recently_visited" table;
362       t#conditional "has_recently_visited" (rv <> []);
363
364       (* If both lists are empty (ie. an empty navigation box would
365        * appear), then disable navigation altogether.
366        *)
367       if wlh = [] && rv = [] then t#conditional "navigation" false
368     );
369
370     (* If we are coming from a search engine then we want to highlight
371      * search terms throughout the whole page ...
372      *)
373     try
374       let referer = Table.get (Request.headers_in r) "Referer" in
375       let search_terms = search_terms_from_referer referer in
376
377       (* Highlight the search terms. *)
378       let xhtml = t#to_string in
379       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
380
381       (* Deliver the page. *)
382       ignore (print_string r xhtml)
383     with
384         Not_found ->
385           (* No referer / no search terms / not a search engine referer. *)
386           ignore (print_string r t#to_string)
387   in
388
389   (* This code generates 404 pages. *)
390   let make_404 () =
391     Request.set_status r 404;           (* Return a 404 error code. *)
392
393     let t = template_404 in
394     t#set "page" page;
395
396     let search_terms =
397       String.map
398         (function
399              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
400            | _ -> ' ') page in
401
402     t#set "search_terms" search_terms;
403
404     t#conditional "can_edit" can_edit;
405     t#conditional "can_manage_users" can_manage_users;
406     t#conditional "has_stats" has_stats;
407
408     q#template t
409   in
410
411   (* Fetch a page by name.  This function can give three answers:
412    * (1) Page fetched OK (fetches some details of the page).
413    * (2) Page is a redirect (fetches the name of the redirect page).
414    * (3) Page not found in database, could be template or 404 error.
415    *)
416   let fetch_page page version allow_redirect =
417     match version with
418       | None ->
419           if allow_redirect then (
420             let sth =
421               dbh#prepare_cached
422                 "select url, redirect, id, title, description,
423                         last_modified_date, css is not null
424                    from pages where hostid = ? and lower (url) = lower (?)" in
425             sth#execute [`Int hostid; `String page];
426             (try
427                (match sth#fetch1 () with
428                 | `String page' :: _ when page <> page' -> (* different case *)
429                     FPExternalRedirect page'
430                 | [ _; `Null; `Int id; `String title; `String description;
431                     `Timestamp last_modified_date; `Bool has_page_css ] ->
432                     FPOK (id, title, description, last_modified_date,
433                           has_page_css)
434                 | _ :: `String redirect :: _ ->
435                     FPInternalRedirect redirect
436                 | xs -> failwith (Dbi.sdebug xs))
437              with
438                Not_found -> FPNotFound)
439           ) else (* redirects not allowed ... *) (
440             let sth =
441               dbh#prepare_cached
442                 "select id, title, description, last_modified_date,
443                         css is not null
444                    from pages where hostid = ? and url = ?" in
445             sth#execute [`Int hostid; `String page];
446             (try
447                (match sth#fetch1 () with
448                 | [ `Int id; `String title; `String description;
449                     `Timestamp last_modified_date; `Bool has_page_css ] ->
450                     FPOK (id, title, description, last_modified_date,
451                           has_page_css)
452                 | xs -> failwith (Dbi.sdebug xs))
453              with
454                  Not_found -> FPNotFound)
455           )
456       | Some version ->
457             let sth =
458               dbh#prepare_cached
459                 "select id, title, description, last_modified_date,
460                         css is not null
461                    from pages
462                   where hostid = ? and id = ? and
463                         (url = ? or url_deleted = ?)" in
464             sth#execute [`Int hostid; `Int version;
465                          `String page; `String page];
466             (try
467                (match sth#fetch1 () with
468                 | [ `Int id; `String title; `String description;
469                     `Timestamp last_modified_date; `Bool has_page_css ] ->
470                     FPOK (id, title, description, last_modified_date,
471                           has_page_css)
472                 | xs -> failwith (Dbi.sdebug xs))
473              with
474                  Not_found -> FPNotFound)
475   in
476
477   (* Here we deal with the complex business of redirects and versions. *)
478   (* Only allow the no_redirect and version syntax for editors. *)
479   let allow_redirect, version =
480     if can_edit then (
481       not (q#param_true "no_redirect"),
482       try Some (int_of_string (q#param "version")) with Not_found -> None
483     ) else
484       (true, None) in
485
486   let rec loop page' i =
487     if i > max_redirect then (
488       error ~title:"Too many redirections" ~back_button:true
489         dbh hostid q
490         ("Too many redirects between pages.  This may happen because " ^
491          "of a cycle of redirections.");
492       return ()
493     ) else
494       match fetch_page page' version allow_redirect with
495         | FPOK (pageid, title, description, last_modified_date, has_page_css)->
496             (* Check if the page is also a template. *)
497             let extension = get_extension page' in
498             make_page title (Some description) (Some pageid)
499               (printable_date last_modified_date) has_page_css
500               version page page' extension
501         | FPInternalRedirect page' ->
502             loop page' (i+1)
503         | FPExternalRedirect page' ->
504             (* This normally happens when a user has request an uppercase
505              * page name.  We redirect to the true (lowercase) version.
506              *)
507             q#redirect ("http://" ^ host.hostname ^ "/" ^ page');
508             return ()
509         | FPNotFound ->
510             (* Might be a templated page with no content in it. *)
511             let extension = get_extension page' in
512             (match extension with
513                | (Some _) as extension ->
514                    let title = page' in
515                    make_page title None None
516                      "Now" false None page page'
517                      extension
518                | None ->
519                    make_404 ())
520   in
521   loop page 0
522
523 let () =
524   register_script ~restrict:[CanView] run