adba28fef59219f574275cab6db946ce98adf587
[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.53 2006/08/14 11:36: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 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 open Cocanwiki_extensions
37 open Cocanwiki_strings
38
39 type fp_status =
40   | FPOK of int32 * string * string * string option * Calendar.t * bool
41       * bool option
42   | FPInternalRedirect of string
43   | FPExternalRedirect of string
44   | FPNotFound
45
46 (* Referer strings which help us decide if the user came from
47  * a search engine and highlight terms in the page appropriately.
48  *)
49 let search_engines = [
50   Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
51   Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
52   Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
53 ]
54 let split_words = Pcre.regexp "\\W+"
55
56 let split_qs_re = Pcre.regexp "\\?"
57
58 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
59
60 let run r (q : cgi) dbh hostid
61     ({ edit_anon = edit_anon; view_anon = view_anon } as host)
62     user =
63   let page = q#param "page" in
64   let page = if page = "" then "index" else page in
65
66   (* The main "page" template is split in two to improve the speed of
67    * delivery of the page.  The very first part ("page_header.html")
68    * contains the page <head>, crucially including all the links to the
69    * stylesheets.  We send this first and flush it out to the client so
70    * that the client can begin requesting stylesheets, background images
71    * and so on.  After this we compose the main page ("page.html") and
72    * send it out second.
73    *)
74
75   let template_page_header =
76     get_template ~page dbh hostid "page_header.html" in
77   let template_page = get_template ~page dbh hostid "page.html" in
78
79   (* This is the simpler template for 404 pages. *)
80   let template_404_header  = get_template dbh hostid "page_404_header.html" in
81   let template_404  = get_template dbh hostid "page_404.html" in
82
83   (* Host-specific fields. *)
84   let rows =
85     PGSQL(dbh)
86       "select feedback_email is not null,
87               mailing_list, navigation
88          from hosts where id = $hostid" in
89   let has_feedback_email, mailing_list, navigation =
90     match rows with
91       | [Some has_feedback_email, mailing_list, navigation] ->
92           has_feedback_email, mailing_list, navigation
93       | _ -> assert false in
94
95   (* User permissions. *)
96   let can_edit = can_edit host user in
97   let can_manage_users = can_manage_users host user in
98
99   (* Do we have a stats page set up? *)
100   let has_stats = server_settings_stats_page dbh <> None in
101
102   (* Given the referer string, return the list of search terms.  If none
103    * can be found, then throws Not_found.
104    *)
105   let search_terms_from_referer referer =
106     let _, argnames =
107       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
108     let url, qs =
109       match Pcre.split ~rex:split_qs_re ~max:2 referer with
110         | [url] | [url;""] -> url, ""
111         | [url;qs] -> url, qs
112         | _ -> assert false in
113     let args = Cgi_args.parse qs in
114     let argname =
115       List.find (fun argname -> List.mem_assoc argname args) argnames in
116     let search_string = List.assoc argname args in
117     Pcre.split ~rex:split_words search_string
118   in
119
120   (* Given a full page of XHTML, highlight search terms found in the
121    * <body> part of the page.
122    *)
123   let highlight_search_terms xhtml search_terms span_class =
124     (* Split the original XHTML into strings and tags.  For example if
125      * the original string is: "This is some <b>bold</b> text.<br/>", then
126      * after this step we will have the following list:
127      * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
128      *)
129     let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
130     let xhtml = Array.to_list xhtml in
131     let xhtml = List.map (fun matches -> matches.(0)) xhtml in
132
133     (* Find the <body> ... </body> tags.  We only want to apply
134      * highlighting to tags within this area.
135      *)
136     let rec list_split f acc = function
137       | [] -> List.rev acc, []
138       | ((x :: _) as xs) when f x -> List.rev acc, xs
139       | x :: xs ->
140           let acc = x :: acc in
141           list_split f acc xs
142     in
143     let head, body =
144       list_split (fun str -> String.starts_with str "<body") [] xhtml in
145     let body, tail =
146       list_split ((=) "</body>") [] body in
147     (* NB: Hopefully, xhtml = head @ body @ tail. *)
148
149     (* The search terms are a list of simple words.  Turn into a big
150      * regular expression, because we want to substitute for each.  We
151      * end up with a regexp like '(word1|word2|word3)'.
152      *)
153     let rex =
154       Pcre.regexp ~flags:[`CASELESS]
155         ("(" ^ String.concat "|" search_terms ^ ")") in
156
157     (* Do the substitution, but only on text, not elements! *)
158     let body =
159       let subst text =
160         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
161       in
162       List.map (fun str ->
163                   if String.length str > 0 && str.[0] != '<' then
164                     Pcre.substitute ~rex ~subst str
165                   else
166                     str) body in
167
168     (* Join the XHTML fragments back together again. *)
169     String.concat "" (List.concat [ head ; body ; tail ])
170   in
171
172   (* Check the templates table for extensions. *)
173   let get_extension url =
174     try
175       let name =
176         List.hd (
177           PGSQL(dbh) "select extension from templates
178                        where $url ~ url_regexp
179                        order by ordering
180                        limit 1"
181         ) in
182       Some (List.assoc name !extensions)
183     with
184       Not_found | ExtList.List.Empty_list | Failure "hd" -> None
185   in
186
187   (* This code generates ordinary pages. *)
188   let make_page title description keywords
189       pageid last_modified_date has_page_css noodp
190       version page page' extension =
191     let t = template_page in
192     let th = template_page_header in
193     t#set "title" title;
194     th#set "title" title;
195     t#set "last_modified_date" last_modified_date;
196
197     (match description with
198          None -> th#conditional "has_description" false
199        | Some description ->
200            th#conditional "has_description" true;
201            th#set "description" description);
202
203     (match keywords with
204          None -> th#conditional "has_keywords" false
205        | Some keywords ->
206            th#conditional "has_keywords" true;
207            th#set "keywords" keywords);
208
209     if page <> page' then (* redirection *) (
210       t#set "page" page';
211       th#set "page" page';
212       t#set "original_page" page; (* XXX title - get it from database *)
213       t#conditional "redirected" true
214     ) else (
215       t#set "page" page;
216       th#set "page" page;
217       t#conditional "redirected" false
218     );
219
220     th#conditional "has_page_css" has_page_css;
221
222     (* If the per-page noodp is not null, set the noodp flag here.  Otherwise
223      * we will use the default (from hosts.global_noodp) which was set
224      * in Cocanwiki_template.
225      *)
226     (match noodp with
227      | None -> ()
228      | Some b -> th#conditional "noodp" b);
229
230     (* Are we showing an old version of the page?  If so, warn. *)
231     (match version with
232          None ->
233            t#conditional "is_old_version" false;
234            th#conditional "is_old_version" false
235        | Some pageid ->
236            t#conditional "is_old_version" true;
237            th#conditional "is_old_version" true;
238            t#set "old_version" (Int32.to_string pageid);
239            th#set "old_version" (Int32.to_string pageid));
240
241     (* Just before we show the header, call any registered pre-page
242      * handlers.  They might want to send cookies.
243      *)
244     List.iter (fun handler ->
245                  handler r q dbh hostid page') !pre_page_handlers;
246
247     (* At this point, we can print out the header and flush it back to
248      * the user, allowing the browser to start fetching stylesheets
249      * and background images while we compose the page.
250      *)
251     q#header ();
252     ignore (print_string r th#to_string);
253     ignore (Request.rflush r);
254
255     t#conditional "has_feedback_email" has_feedback_email;
256     t#conditional "mailing_list" mailing_list;
257     t#conditional "navigation" navigation;
258
259     t#conditional "can_edit" can_edit;
260     t#conditional "can_manage_users" can_manage_users;
261     t#conditional "has_stats" has_stats;
262
263     (* Pull out the sections in this page. *)
264     let sections =
265       match pageid with
266           None -> []
267         | Some pageid ->
268             let rows = PGSQL(dbh)
269               "select ordering, sectionname, content, divname, jsgo
270                  from contents where pageid = $pageid order by ordering" in
271
272             List.map
273               (fun (ordering, sectionname, content, divname, jsgo) ->
274                  let divname, has_divname =
275                    match divname with
276                    | None -> "", false
277                    | Some divname -> divname, true in
278                  let jsgo, has_jsgo =
279                    match jsgo with
280                    | None -> "", false
281                    | Some jsgo -> jsgo, true in
282                  let sectionname, has_sectionname =
283                    match sectionname with
284                    | None -> "", false
285                    | Some sectionname -> sectionname, true in
286                  let linkname = linkname_of_sectionname sectionname in
287                  [ "ordering", Template.VarString (Int32.to_string ordering);
288                    "has_sectionname",
289                      Template.VarConditional has_sectionname;
290                    "sectionname", Template.VarString sectionname;
291                    "linkname", Template.VarString linkname;
292                    "content",
293                      Template.VarString
294                        (Wikilib.xhtml_of_content r dbh hostid content);
295                    "has_divname", Template.VarConditional has_divname;
296                    "divname", Template.VarString divname;
297                    "has_jsgo", Template.VarConditional has_jsgo;
298                    "jsgo", Template.VarString jsgo ]) rows in
299
300     (* Call an extension to generate the first section in this page? *)
301     let sections =
302       match extension with
303           None -> sections
304         | Some extension ->
305             let content = extension r dbh hostid page' in
306             let section = [
307               "ordering", Template.VarString "0";
308               "has_sectionname", Template.VarConditional false;
309               "linkname", Template.VarString "";
310               "content", Template.VarString content;
311               "has_divname", Template.VarConditional true;
312               "divname", Template.VarString "form_div";
313               "has_jsgo", Template.VarConditional false;
314               "jsgo", Template.VarString "";
315             ] in
316             section :: sections in
317
318     t#table "sections" sections;
319
320     (* Login status. *)
321     (match user with
322          Anonymous ->
323            t#conditional "user_logged_in" false
324        | User (_, username, _, _) ->
325            t#conditional "user_logged_in" true;
326            t#set "username" username);
327
328     (* Can anonymous users create accounts?  If not them we don't
329      * want to offer to create accounts for them.
330      *)
331     t#conditional "create_account_anon" host.create_account_anon;
332
333     (* If logged in, we want to update the recently_visited table. *)
334     if pageid <> None then (
335       match user with
336         | User (userid, _, _, _) ->
337             (try
338                PGSQL(dbh)
339                  "delete from recently_visited
340                    where hostid = $hostid and userid = $userid
341                      and url = $page'";
342                PGSQL(dbh)
343                  "insert into recently_visited (hostid, userid, url)
344                   values ($hostid, $userid, $page')";
345                PGOCaml.commit dbh;
346              with
347                exn ->
348                  (* Exceptions here are non-fatal.  Just print them. *)
349                  prerr_endline "exception updating recently_visited:";
350                  prerr_endline (Printexc.to_string exn);
351                  PGOCaml.rollback dbh;
352             );
353             PGOCaml.begin_work dbh;
354         | _ -> ()
355     );
356
357     (* Navigation links. *)
358     if navigation then (
359       let max_links = 18 in             (* Show no more links than this. *)
360
361       (* What links here. *)
362       let wlh = what_links_here dbh hostid page' in
363       let wlh = List.take max_links wlh in
364       let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
365
366       let rv =
367         match user with
368           | User (userid, _, _, _) ->
369               (* Recently visited URLs, but don't repeat any from the 'what
370                * links here' section, and don't link to self.
371                *)
372               let not_urls = page' :: wlh_urls in
373               let limit = Int32.of_int (max_links - List.length wlh_urls) in
374               let rows =
375                 PGSQL(dbh)
376                   "select rv.url, p.title, rv.visit_time
377                      from recently_visited rv, pages p
378                     where rv.hostid = $hostid and rv.userid = $userid
379                       and rv.url not in $@not_urls
380                       and rv.hostid = p.hostid and rv.url = p.url
381                     order by 3 desc
382                     limit $limit" in
383               List.map (
384                 fun (url, title, _) -> url, title
385               ) rows
386           | _ -> [] in
387
388       (* Links to page. *)
389       let f (page, title) = [ "page", Template.VarString page;
390                               "title", Template.VarString title ] in
391       let table = List.map f wlh in
392       t#table "what_links_here" table;
393       t#conditional "has_what_links_here" (wlh <> []);
394
395       let table = List.map f rv in
396       t#table "recently_visited" table;
397       t#conditional "has_recently_visited" (rv <> []);
398
399       (* If both lists are empty (ie. an empty navigation box would
400        * appear), then disable navigation altogether.
401        *)
402       if wlh = [] && rv = [] then t#conditional "navigation" false
403     );
404
405     (* If we are coming from a search engine then we want to highlight
406      * search terms throughout the whole page ...
407      *)
408     try
409       let referer = Table.get (Request.headers_in r) "Referer" in
410       let search_terms = search_terms_from_referer referer in
411
412       (* Highlight the search terms. *)
413       let xhtml = t#to_string in
414       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
415
416       (* Deliver the page. *)
417       ignore (print_string r xhtml)
418     with
419         Not_found ->
420           (* No referer / no search terms / not a search engine referer. *)
421           ignore (print_string r t#to_string)
422   in
423
424   (* This code generates 404 pages. *)
425   let make_404 () =
426     Request.set_status r 404;           (* Return a 404 error code. *)
427
428     let th = template_404_header in
429     th#set "page" page;
430
431     let search_terms =
432       String.map
433         (function
434              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
435            | _ -> ' ') page in
436
437     th#set "search_terms" search_terms;
438
439     (* Flush out the header while we start the search. *)
440     q#header ();
441     ignore (print_string r th#to_string);
442     ignore (Request.rflush r);
443
444     let t = template_404 in
445     t#set "query" search_terms;
446     t#set "canonical_hostname" host.canonical_hostname;
447
448     (* This is a simplified version of the code in search.ml. *)
449     let have_results =
450       (* Get the keywords from the query string. *)
451       let keywords = Pcre.split ~rex:split_words search_terms in
452       let keywords =
453         List.filter (fun s -> not (string_is_whitespace s)) keywords in
454       let keywords = List.map String.lowercase keywords in
455
456       (* Turn the keywords into a tsearch2 ts_query string. *)
457       let tsquery = String.concat "&" keywords in
458
459       (* Search the titles first. *)
460       let rows =
461         PGSQL(dbh)
462             "select url, title, last_modified_date,
463                     (lower (title) = lower ($search_terms)) as exact
464                from pages
465               where hostid = $hostid
466                 and url is not null
467                 and redirect is null
468                 and title_description_fti @@ to_tsquery ('default', $tsquery)
469               order by exact desc, last_modified_date desc, title" in
470
471       let titles =
472         List.map (function
473                   | (Some url, title, last_modified, _) ->
474                       url, title, last_modified
475                   | _ -> assert false) rows in
476
477       let have_titles = titles <> [] in
478       t#conditional "have_titles" have_titles;
479
480       (* Search the contents. *)
481       let rows =
482         PGSQL(dbh)
483           "select c.id, p.url, p.title, p.last_modified_date
484              from contents c, pages p
485             where c.pageid = p.id
486               and p.hostid = $hostid
487               and url is not null
488               and p.redirect is null
489               and c.content_fti @@ to_tsquery ('default', $tsquery)
490             order by p.last_modified_date desc, p.title
491             limit 50" in
492
493       let contents =
494         List.map (function
495                   | (contentid, Some url, title, last_modified) ->
496                       contentid, url, title, last_modified
497                   | _ -> assert false) rows in
498
499       let have_contents = contents <> [] in
500       t#conditional "have_contents" have_contents;
501
502       (* Pull out the actual text which matched so we can generate a summary.
503        * XXX tsearch2 can actually do better than this by emboldening
504        * the text which maps.
505        *)
506       let content_map =
507         if contents = [] then []
508         else (
509           let rows =
510             let contentids =
511               List.map (fun (contentid, _,_,_) -> contentid) contents in
512             PGSQL(dbh)
513               "select id, sectionname, content from contents
514                 where id in $@contentids" in
515           List.map (fun (id, sectionname, content) ->
516                       id, (sectionname, content)) rows
517         ) in
518
519       (* Generate the final tables. *)
520       let table =
521         List.map (fun (url, title, last_modified) ->
522                     let last_modified = printable_date last_modified in
523                     [ "url", Template.VarString url;
524                       "title", Template.VarString title;
525                       "last_modified", Template.VarString last_modified ]
526                  ) titles in
527       t#table "titles" table;
528
529       let table =
530         List.map
531           (fun (contentid, url, title, last_modified) ->
532              let sectionname, content = List.assoc contentid content_map in
533              let have_sectionname, sectionname =
534                match sectionname with
535                  None -> false, ""
536                | Some sectionname -> true, sectionname in
537              let content =
538                truncate 160
539                  (Wikilib.text_of_xhtml
540                     (Wikilib.xhtml_of_content r dbh hostid content)) in
541              let linkname = linkname_of_sectionname sectionname in
542              let last_modified = printable_date last_modified in
543              [ "url", Template.VarString url;
544                "title", Template.VarString title;
545                "have_sectionname", Template.VarConditional have_sectionname;
546                "sectionname", Template.VarString sectionname;
547                "linkname", Template.VarString linkname;
548                "content", Template.VarString content;
549                "last_modified", Template.VarString last_modified ]
550           ) contents in
551       t#table "contents" table;
552
553       (* Do we have any results? *)
554       let have_results = have_titles || have_contents in
555       have_results in
556     t#conditional "have_results" have_results;
557
558     (* Deliver the rest of the page. *)
559     ignore (print_string r t#to_string)
560   in
561
562   (* Fetch a page by name.  This function can give three answers:
563    * (1) Page fetched OK (fetches some details of the page).
564    * (2) Page is a redirect (fetches the name of the redirect page).
565    * (3) Page not found in database, could be template or 404 error.
566    *)
567   let fetch_page page version allow_redirect =
568     match version with
569       | None ->
570           if allow_redirect then (
571             let rows = PGSQL(dbh)
572               "select url, redirect, id, title, description, keywords,
573                       last_modified_date, css is not null, noodp
574                  from pages
575                 where hostid = $hostid and lower (url) = lower ($page)" in
576             match rows with
577             | [Some page', _, _, _, _, _, _, _, _]
578                 when page <> page' -> (* different case *)
579                 FPExternalRedirect page'
580             | [ _, None, id, title, description, keywords,
581                 last_modified_date, has_page_css, noodp ] ->
582                 let has_page_css = Option.get has_page_css in
583                 FPOK (id, title, description, keywords, last_modified_date,
584                       has_page_css, noodp)
585             | [_, Some redirect, _, _, _, _, _, _, _] ->
586                 FPInternalRedirect redirect
587             | [] -> FPNotFound
588             | _ -> assert false
589           ) else (* redirects not allowed ... *) (
590             let rows = PGSQL(dbh)
591               "select id, title, description, keywords, last_modified_date,
592                       css is not null, noodp
593                  from pages where hostid = $hostid and url = $page" in
594             match rows with
595             | [ id, title, description, keywords,
596                 last_modified_date, has_page_css, noodp ] ->
597                 let has_page_css = Option.get has_page_css in
598                 FPOK (id, title, description, keywords, last_modified_date,
599                       has_page_css, noodp)
600             | [] -> FPNotFound
601             | _ -> assert false
602           )
603       | Some version ->
604           let rows = PGSQL(dbh)
605             "select id, title, description, keywords, last_modified_date,
606                     css is not null, noodp
607                from pages
608               where hostid = $hostid and id = $version and
609                     (url = $page or url_deleted = $page)" in
610           match rows with
611           | [ id, title, description, keywords,
612               last_modified_date, has_page_css, noodp ] ->
613               let has_page_css = Option.get has_page_css in
614               FPOK (id, title, description, keywords, last_modified_date,
615                     has_page_css, noodp)
616           | [] -> FPNotFound
617           | _ -> assert false
618   in
619
620   (* Here we deal with the complex business of redirects and versions. *)
621   (* Only allow the no_redirect and version syntax for editors. *)
622   let allow_redirect, version =
623     if can_edit then (
624       not (q#param_true "no_redirect"),
625       try Some (Int32.of_string (q#param "version")) with Not_found -> None
626     ) else
627       (true, None) in
628
629   let rec loop page' i =
630     if i > max_redirect then (
631       error ~title:"Too many redirections" ~back_button:true
632         dbh hostid q
633         ("Too many redirects between pages.  This may happen because " ^
634          "of a cycle of redirections.");
635       return ()
636     ) else
637       match fetch_page page' version allow_redirect with
638         | FPOK (pageid, title, description, keywords,
639                 last_modified_date, has_page_css, noodp)->
640             (* Check if the page is also a template. *)
641             let extension = get_extension page' in
642             make_page title (Some description) keywords (Some pageid)
643               (printable_date last_modified_date) has_page_css noodp
644               version page page' extension
645         | FPInternalRedirect page' ->
646             loop page' (i+1)
647         | FPExternalRedirect page' ->
648             (* This normally happens when a user has requested an uppercase
649              * page name.  We redirect to the true (lowercase) version.
650              *)
651             q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
652         | FPNotFound ->
653             (* Might be a templated page with no content in it. *)
654             let extension = get_extension page' in
655             (match extension with
656                | (Some _) as extension ->
657                    let title = page' in
658                    make_page title None None None
659                      "Now" false None None page page'
660                      extension
661                | None ->
662                    make_404 ())
663   in
664   loop page 0
665
666 let () =
667   register_script ~restrict:[CanView] run