Added <meta keywords> on pages.
[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.52 2006/08/04 12:45:31 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   | FPInternalRedirect of string
42   | FPExternalRedirect of string
43   | FPNotFound
44
45 (* Referer strings which help us decide if the user came from
46  * a search engine and highlight terms in the page appropriately.
47  *)
48 let search_engines = [
49   Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
50   Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
51   Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
52 ]
53 let split_words = Pcre.regexp "\\W+"
54
55 let split_qs_re = Pcre.regexp "\\?"
56
57 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
58
59 let run r (q : cgi) dbh hostid
60     ({ edit_anon = edit_anon; view_anon = view_anon } as host)
61     user =
62   let page = q#param "page" in
63   let page = if page = "" then "index" else page in
64
65   (* The main "page" template is split in two to improve the speed of
66    * delivery of the page.  The very first part ("page_header.html")
67    * contains the page <head>, crucially including all the links to the
68    * stylesheets.  We send this first and flush it out to the client so
69    * that the client can begin requesting stylesheets, background images
70    * and so on.  After this we compose the main page ("page.html") and
71    * send it out second.
72    *)
73
74   let template_page_header =
75     get_template ~page dbh hostid "page_header.html" in
76   let template_page = get_template ~page dbh hostid "page.html" in
77
78   (* This is the simpler template for 404 pages. *)
79   let template_404_header  = get_template dbh hostid "page_404_header.html" in
80   let template_404  = get_template dbh hostid "page_404.html" in
81
82   (* Host-specific fields. *)
83   let rows =
84     PGSQL(dbh)
85       "select feedback_email is not null,
86               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
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     (* Are we showing an old version of the page?  If so, warn. *)
222     (match version with
223          None ->
224            t#conditional "is_old_version" false;
225            th#conditional "is_old_version" false
226        | Some pageid ->
227            t#conditional "is_old_version" true;
228            th#conditional "is_old_version" true;
229            t#set "old_version" (Int32.to_string pageid);
230            th#set "old_version" (Int32.to_string pageid));
231
232     (* Just before we show the header, call any registered pre-page
233      * handlers.  They might want to send cookies.
234      *)
235     List.iter (fun handler ->
236                  handler r q dbh hostid page') !pre_page_handlers;
237
238     (* At this point, we can print out the header and flush it back to
239      * the user, allowing the browser to start fetching stylesheets
240      * and background images while we compose the page.
241      *)
242     q#header ();
243     ignore (print_string r th#to_string);
244     ignore (Request.rflush r);
245
246     t#conditional "has_feedback_email" has_feedback_email;
247     t#conditional "mailing_list" mailing_list;
248     t#conditional "navigation" navigation;
249
250     t#conditional "can_edit" can_edit;
251     t#conditional "can_manage_users" can_manage_users;
252     t#conditional "has_stats" has_stats;
253
254     (* Pull out the sections in this page. *)
255     let sections =
256       match pageid with
257           None -> []
258         | Some pageid ->
259             let rows = PGSQL(dbh)
260               "select ordering, sectionname, content, divname, jsgo
261                  from contents where pageid = $pageid order by ordering" in
262
263             List.map
264               (fun (ordering, sectionname, content, divname, jsgo) ->
265                  let divname, has_divname =
266                    match divname with
267                    | None -> "", false
268                    | Some divname -> divname, true in
269                  let jsgo, has_jsgo =
270                    match jsgo with
271                    | None -> "", false
272                    | Some jsgo -> jsgo, true in
273                  let sectionname, has_sectionname =
274                    match sectionname with
275                    | None -> "", false
276                    | Some sectionname -> sectionname, true in
277                  let linkname = linkname_of_sectionname sectionname in
278                  [ "ordering", Template.VarString (Int32.to_string ordering);
279                    "has_sectionname",
280                      Template.VarConditional has_sectionname;
281                    "sectionname", Template.VarString sectionname;
282                    "linkname", Template.VarString linkname;
283                    "content",
284                      Template.VarString
285                        (Wikilib.xhtml_of_content r dbh hostid content);
286                    "has_divname", Template.VarConditional has_divname;
287                    "divname", Template.VarString divname;
288                    "has_jsgo", Template.VarConditional has_jsgo;
289                    "jsgo", Template.VarString jsgo ]) rows in
290
291     (* Call an extension to generate the first section in this page? *)
292     let sections =
293       match extension with
294           None -> sections
295         | Some extension ->
296             let content = extension r dbh hostid page' in
297             let section = [
298               "ordering", Template.VarString "0";
299               "has_sectionname", Template.VarConditional false;
300               "linkname", Template.VarString "";
301               "content", Template.VarString content;
302               "has_divname", Template.VarConditional true;
303               "divname", Template.VarString "form_div";
304               "has_jsgo", Template.VarConditional false;
305               "jsgo", Template.VarString "";
306             ] in
307             section :: sections in
308
309     t#table "sections" sections;
310
311     (* Login status. *)
312     (match user with
313          Anonymous ->
314            t#conditional "user_logged_in" false
315        | User (_, username, _, _) ->
316            t#conditional "user_logged_in" true;
317            t#set "username" username);
318
319     (* Can anonymous users create accounts?  If not them we don't
320      * want to offer to create accounts for them.
321      *)
322     t#conditional "create_account_anon" host.create_account_anon;
323
324     (* If logged in, we want to update the recently_visited table. *)
325     if pageid <> None then (
326       match user with
327         | User (userid, _, _, _) ->
328             (try
329                PGSQL(dbh)
330                  "delete from recently_visited
331                    where hostid = $hostid and userid = $userid
332                      and url = $page'";
333                PGSQL(dbh)
334                  "insert into recently_visited (hostid, userid, url)
335                   values ($hostid, $userid, $page')";
336                PGOCaml.commit dbh;
337              with
338                exn ->
339                  (* Exceptions here are non-fatal.  Just print them. *)
340                  prerr_endline "exception updating recently_visited:";
341                  prerr_endline (Printexc.to_string exn);
342                  PGOCaml.rollback dbh;
343             );
344             PGOCaml.begin_work dbh;
345         | _ -> ()
346     );
347
348     (* Navigation links. *)
349     if navigation then (
350       let max_links = 18 in             (* Show no more links than this. *)
351
352       (* What links here. *)
353       let wlh = what_links_here dbh hostid page' in
354       let wlh = List.take max_links wlh in
355       let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
356
357       let rv =
358         match user with
359           | User (userid, _, _, _) ->
360               (* Recently visited URLs, but don't repeat any from the 'what
361                * links here' section, and don't link to self.
362                *)
363               let not_urls = page' :: wlh_urls in
364               let limit = Int32.of_int (max_links - List.length wlh_urls) in
365               let rows =
366                 PGSQL(dbh)
367                   "select rv.url, p.title, rv.visit_time
368                      from recently_visited rv, pages p
369                     where rv.hostid = $hostid and rv.userid = $userid
370                       and rv.url not in $@not_urls
371                       and rv.hostid = p.hostid and rv.url = p.url
372                     order by 3 desc
373                     limit $limit" in
374               List.map (
375                 fun (url, title, _) -> url, title
376               ) rows
377           | _ -> [] in
378
379       (* Links to page. *)
380       let f (page, title) = [ "page", Template.VarString page;
381                               "title", Template.VarString title ] in
382       let table = List.map f wlh in
383       t#table "what_links_here" table;
384       t#conditional "has_what_links_here" (wlh <> []);
385
386       let table = List.map f rv in
387       t#table "recently_visited" table;
388       t#conditional "has_recently_visited" (rv <> []);
389
390       (* If both lists are empty (ie. an empty navigation box would
391        * appear), then disable navigation altogether.
392        *)
393       if wlh = [] && rv = [] then t#conditional "navigation" false
394     );
395
396     (* If we are coming from a search engine then we want to highlight
397      * search terms throughout the whole page ...
398      *)
399     try
400       let referer = Table.get (Request.headers_in r) "Referer" in
401       let search_terms = search_terms_from_referer referer in
402
403       (* Highlight the search terms. *)
404       let xhtml = t#to_string in
405       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
406
407       (* Deliver the page. *)
408       ignore (print_string r xhtml)
409     with
410         Not_found ->
411           (* No referer / no search terms / not a search engine referer. *)
412           ignore (print_string r t#to_string)
413   in
414
415   (* This code generates 404 pages. *)
416   let make_404 () =
417     Request.set_status r 404;           (* Return a 404 error code. *)
418
419     let th = template_404_header in
420     th#set "page" page;
421
422     let search_terms =
423       String.map
424         (function
425              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
426            | _ -> ' ') page in
427
428     th#set "search_terms" search_terms;
429
430     (* Flush out the header while we start the search. *)
431     q#header ();
432     ignore (print_string r th#to_string);
433     ignore (Request.rflush r);
434
435     let t = template_404 in
436     t#set "query" search_terms;
437     t#set "canonical_hostname" host.canonical_hostname;
438
439     (* This is a simplified version of the code in search.ml. *)
440     let have_results =
441       (* Get the keywords from the query string. *)
442       let keywords = Pcre.split ~rex:split_words search_terms in
443       let keywords =
444         List.filter (fun s -> not (string_is_whitespace s)) keywords in
445       let keywords = List.map String.lowercase keywords in
446
447       (* Turn the keywords into a tsearch2 ts_query string. *)
448       let tsquery = String.concat "&" keywords in
449
450       (* Search the titles first. *)
451       let rows =
452         PGSQL(dbh)
453             "select url, title, last_modified_date,
454                     (lower (title) = lower ($search_terms)) as exact
455                from pages
456               where hostid = $hostid
457                 and url is not null
458                 and redirect is null
459                 and title_description_fti @@ to_tsquery ('default', $tsquery)
460               order by exact desc, last_modified_date desc, title" in
461
462       let titles =
463         List.map (function
464                   | (Some url, title, last_modified, _) ->
465                       url, title, last_modified
466                   | _ -> assert false) rows in
467
468       let have_titles = titles <> [] in
469       t#conditional "have_titles" have_titles;
470
471       (* Search the contents. *)
472       let rows =
473         PGSQL(dbh)
474           "select c.id, p.url, p.title, p.last_modified_date
475              from contents c, pages p
476             where c.pageid = p.id
477               and p.hostid = $hostid
478               and url is not null
479               and p.redirect is null
480               and c.content_fti @@ to_tsquery ('default', $tsquery)
481             order by p.last_modified_date desc, p.title
482             limit 50" in
483
484       let contents =
485         List.map (function
486                   | (contentid, Some url, title, last_modified) ->
487                       contentid, url, title, last_modified
488                   | _ -> assert false) rows in
489
490       let have_contents = contents <> [] in
491       t#conditional "have_contents" have_contents;
492
493       (* Pull out the actual text which matched so we can generate a summary.
494        * XXX tsearch2 can actually do better than this by emboldening
495        * the text which maps.
496        *)
497       let content_map =
498         if contents = [] then []
499         else (
500           let rows =
501             let contentids =
502               List.map (fun (contentid, _,_,_) -> contentid) contents in
503             PGSQL(dbh)
504               "select id, sectionname, content from contents
505                 where id in $@contentids" in
506           List.map (fun (id, sectionname, content) ->
507                       id, (sectionname, content)) rows
508         ) in
509
510       (* Generate the final tables. *)
511       let table =
512         List.map (fun (url, title, last_modified) ->
513                     let last_modified = printable_date last_modified in
514                     [ "url", Template.VarString url;
515                       "title", Template.VarString title;
516                       "last_modified", Template.VarString last_modified ]
517                  ) titles in
518       t#table "titles" table;
519
520       let table =
521         List.map
522           (fun (contentid, url, title, last_modified) ->
523              let sectionname, content = List.assoc contentid content_map in
524              let have_sectionname, sectionname =
525                match sectionname with
526                  None -> false, ""
527                | Some sectionname -> true, sectionname in
528              let content =
529                truncate 160
530                  (Wikilib.text_of_xhtml
531                     (Wikilib.xhtml_of_content r dbh hostid content)) in
532              let linkname = linkname_of_sectionname sectionname in
533              let last_modified = printable_date last_modified in
534              [ "url", Template.VarString url;
535                "title", Template.VarString title;
536                "have_sectionname", Template.VarConditional have_sectionname;
537                "sectionname", Template.VarString sectionname;
538                "linkname", Template.VarString linkname;
539                "content", Template.VarString content;
540                "last_modified", Template.VarString last_modified ]
541           ) contents in
542       t#table "contents" table;
543
544       (* Do we have any results? *)
545       let have_results = have_titles || have_contents in
546       have_results in
547     t#conditional "have_results" have_results;
548
549     (* Deliver the rest of the page. *)
550     ignore (print_string r t#to_string)
551   in
552
553   (* Fetch a page by name.  This function can give three answers:
554    * (1) Page fetched OK (fetches some details of the page).
555    * (2) Page is a redirect (fetches the name of the redirect page).
556    * (3) Page not found in database, could be template or 404 error.
557    *)
558   let fetch_page page version allow_redirect =
559     match version with
560       | None ->
561           if allow_redirect then (
562             let rows = PGSQL(dbh)
563               "select url, redirect, id, title, description, keywords,
564                       last_modified_date, css is not null
565                  from pages
566                 where hostid = $hostid and lower (url) = lower ($page)" in
567             match rows with
568             | [Some page', _, _, _, _, _, _, _]
569                 when page <> page' -> (* different case *)
570                 FPExternalRedirect page'
571             | [ _, None, id, title, description, keywords,
572                 last_modified_date, has_page_css ] ->
573                 let has_page_css = Option.get has_page_css in
574                 FPOK (id, title, description, keywords, last_modified_date,
575                       has_page_css)
576             | [_, Some redirect, _, _, _, _, _, _] ->
577                 FPInternalRedirect redirect
578             | [] -> FPNotFound
579             | _ -> assert false
580           ) else (* redirects not allowed ... *) (
581             let rows = PGSQL(dbh)
582               "select id, title, description, keywords, last_modified_date,
583                       css is not null
584                  from pages where hostid = $hostid and url = $page" in
585             match rows with
586             | [ id, title, description, keywords,
587                 last_modified_date, has_page_css ] ->
588                 let has_page_css = Option.get has_page_css in
589                 FPOK (id, title, description, keywords, last_modified_date,
590                       has_page_css)
591             | [] -> FPNotFound
592             | _ -> assert false
593           )
594       | Some version ->
595           let rows = PGSQL(dbh)
596             "select id, title, description, keywords, last_modified_date,
597                     css is not null
598                from pages
599               where hostid = $hostid and id = $version and
600                     (url = $page or url_deleted = $page)" in
601           match rows with
602           | [ id, title, description, keywords,
603               last_modified_date, has_page_css ] ->
604               let has_page_css = Option.get has_page_css in
605               FPOK (id, title, description, keywords, last_modified_date,
606                     has_page_css)
607           | [] -> FPNotFound
608           | _ -> assert false
609   in
610
611   (* Here we deal with the complex business of redirects and versions. *)
612   (* Only allow the no_redirect and version syntax for editors. *)
613   let allow_redirect, version =
614     if can_edit then (
615       not (q#param_true "no_redirect"),
616       try Some (Int32.of_string (q#param "version")) with Not_found -> None
617     ) else
618       (true, None) in
619
620   let rec loop page' i =
621     if i > max_redirect then (
622       error ~title:"Too many redirections" ~back_button:true
623         dbh hostid q
624         ("Too many redirects between pages.  This may happen because " ^
625          "of a cycle of redirections.");
626       return ()
627     ) else
628       match fetch_page page' version allow_redirect with
629         | FPOK (pageid, title, description, keywords,
630                 last_modified_date, has_page_css)->
631             (* Check if the page is also a template. *)
632             let extension = get_extension page' in
633             make_page title (Some description) keywords (Some pageid)
634               (printable_date last_modified_date) has_page_css
635               version page page' extension
636         | FPInternalRedirect page' ->
637             loop page' (i+1)
638         | FPExternalRedirect page' ->
639             (* This normally happens when a user has requested an uppercase
640              * page name.  We redirect to the true (lowercase) version.
641              *)
642             q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
643         | FPNotFound ->
644             (* Might be a templated page with no content in it. *)
645             let extension = get_extension page' in
646             (match extension with
647                | (Some _) as extension ->
648                    let title = page' in
649                    make_page title None None None
650                      "Now" false None page page'
651                      extension
652                | None ->
653                    make_404 ())
654   in
655   loop page 0
656
657 let () =
658   register_script ~restrict:[CanView] run