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