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