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 $
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.
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.
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.
31 open Cocanwiki_template
34 open Cocanwiki_server_settings
36 open Cocanwiki_extensions
37 open Cocanwiki_strings
40 | FPOK of int32 * string * string * string option * Calendar.t * bool
42 | FPInternalRedirect of string
43 | FPExternalRedirect of string
46 (* Referer strings which help us decide if the user came from
47 * a search engine and highlight terms in the page appropriately.
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" ]
54 let split_words = Pcre.regexp "\\W+"
56 let split_qs_re = Pcre.regexp "\\?"
58 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
60 let run r (q : cgi) dbh hostid
61 ({ edit_anon = edit_anon; view_anon = view_anon } as host)
63 let page = q#param "page" in
64 let page = if page = "" then "index" else page in
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
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
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
83 (* Host-specific fields. *)
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 =
91 | [Some has_feedback_email, mailing_list, navigation] ->
92 has_feedback_email, mailing_list, navigation
93 | _ -> assert false in
95 (* User permissions. *)
96 let can_edit = can_edit host user in
97 let can_manage_users = can_manage_users host user in
99 (* Do we have a stats page set up? *)
100 let has_stats = server_settings_stats_page dbh <> None in
102 (* Given the referer string, return the list of search terms. If none
103 * can be found, then throws Not_found.
105 let search_terms_from_referer referer =
107 List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
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
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
120 (* Given a full page of XHTML, highlight search terms found in the
121 * <body> part of the page.
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/>" ]
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
133 (* Find the <body> ... </body> tags. We only want to apply
134 * highlighting to tags within this area.
136 let rec list_split f acc = function
137 | [] -> List.rev acc, []
138 | ((x :: _) as xs) when f x -> List.rev acc, xs
140 let acc = x :: acc in
144 list_split (fun str -> String.starts_with str "<body") [] xhtml in
146 list_split ((=) "</body>") [] body in
147 (* NB: Hopefully, xhtml = head @ body @ tail. *)
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)'.
154 Pcre.regexp ~flags:[`CASELESS]
155 ("(" ^ String.concat "|" search_terms ^ ")") in
157 (* Do the substitution, but only on text, not elements! *)
160 "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
163 if String.length str > 0 && str.[0] != '<' then
164 Pcre.substitute ~rex ~subst str
168 (* Join the XHTML fragments back together again. *)
169 String.concat "" (List.concat [ head ; body ; tail ])
172 (* Check the templates table for extensions. *)
173 let get_extension url =
177 PGSQL(dbh) "select extension from templates
178 where $url ~ url_regexp
182 Some (List.assoc name !extensions)
184 Not_found | ExtList.List.Empty_list | Failure "hd" -> None
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
194 th#set "title" title;
195 t#set "last_modified_date" last_modified_date;
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);
204 None -> th#conditional "has_keywords" false
206 th#conditional "has_keywords" true;
207 th#set "keywords" keywords);
209 if page <> page' then (* redirection *) (
212 t#set "original_page" page; (* XXX title - get it from database *)
213 t#conditional "redirected" true
217 t#conditional "redirected" false
220 th#conditional "has_page_css" has_page_css;
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.
228 | Some b -> th#conditional "noodp" b);
230 (* Are we showing an old version of the page? If so, warn. *)
233 t#conditional "is_old_version" false;
234 th#conditional "is_old_version" false
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));
241 (* Just before we show the header, call any registered pre-page
242 * handlers. They might want to send cookies.
244 List.iter (fun handler ->
245 handler r q dbh hostid page') !pre_page_handlers;
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.
252 ignore (print_string r th#to_string);
253 ignore (Request.rflush r);
255 t#conditional "has_feedback_email" has_feedback_email;
256 t#conditional "mailing_list" mailing_list;
257 t#conditional "navigation" navigation;
259 t#conditional "can_edit" can_edit;
260 t#conditional "can_manage_users" can_manage_users;
261 t#conditional "has_stats" has_stats;
263 (* Pull out the sections in this page. *)
268 let rows = PGSQL(dbh)
269 "select ordering, sectionname, content, divname, jsgo
270 from contents where pageid = $pageid order by ordering" in
273 (fun (ordering, sectionname, content, divname, jsgo) ->
274 let divname, has_divname =
277 | Some divname -> divname, true in
281 | Some jsgo -> jsgo, true in
282 let sectionname, has_sectionname =
283 match sectionname with
285 | Some sectionname -> sectionname, true in
286 let linkname = linkname_of_sectionname sectionname in
287 [ "ordering", Template.VarString (Int32.to_string ordering);
289 Template.VarConditional has_sectionname;
290 "sectionname", Template.VarString sectionname;
291 "linkname", Template.VarString linkname;
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
300 (* Call an extension to generate the first section in this page? *)
305 let content = extension r dbh hostid page' in
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 "";
316 section :: sections in
318 t#table "sections" sections;
323 t#conditional "user_logged_in" false
324 | User (_, username, _, _) ->
325 t#conditional "user_logged_in" true;
326 t#set "username" username);
328 (* Can anonymous users create accounts? If not them we don't
329 * want to offer to create accounts for them.
331 t#conditional "create_account_anon" host.create_account_anon;
333 (* If logged in, we want to update the recently_visited table. *)
334 if pageid <> None then (
336 | User (userid, _, _, _) ->
339 "delete from recently_visited
340 where hostid = $hostid and userid = $userid
343 "insert into recently_visited (hostid, userid, url)
344 values ($hostid, $userid, $page')";
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;
353 PGOCaml.begin_work dbh;
357 (* Navigation links. *)
359 let max_links = 18 in (* Show no more links than this. *)
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 ... *)
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.
372 let not_urls = page' :: wlh_urls in
373 let limit = Int32.of_int (max_links - List.length wlh_urls) in
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
384 fun (url, title, _) -> url, title
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 <> []);
395 let table = List.map f rv in
396 t#table "recently_visited" table;
397 t#conditional "has_recently_visited" (rv <> []);
399 (* If both lists are empty (ie. an empty navigation box would
400 * appear), then disable navigation altogether.
402 if wlh = [] && rv = [] then t#conditional "navigation" false
405 (* If we are coming from a search engine then we want to highlight
406 * search terms throughout the whole page ...
409 let referer = Table.get (Request.headers_in r) "Referer" in
410 let search_terms = search_terms_from_referer referer in
412 (* Highlight the search terms. *)
413 let xhtml = t#to_string in
414 let xhtml = highlight_search_terms xhtml search_terms "search_term" in
416 (* Deliver the page. *)
417 ignore (print_string r xhtml)
420 (* No referer / no search terms / not a search engine referer. *)
421 ignore (print_string r t#to_string)
424 (* This code generates 404 pages. *)
426 Request.set_status r 404; (* Return a 404 error code. *)
428 let th = template_404_header in
434 ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
437 th#set "search_terms" search_terms;
439 (* Flush out the header while we start the search. *)
441 ignore (print_string r th#to_string);
442 ignore (Request.rflush r);
444 let t = template_404 in
445 t#set "query" search_terms;
446 t#set "canonical_hostname" host.canonical_hostname;
448 (* This is a simplified version of the code in search.ml. *)
450 (* Get the keywords from the query string. *)
451 let keywords = Pcre.split ~rex:split_words search_terms in
453 List.filter (fun s -> not (string_is_whitespace s)) keywords in
454 let keywords = List.map String.lowercase keywords in
456 (* Turn the keywords into a tsearch2 ts_query string. *)
457 let tsquery = String.concat "&" keywords in
459 (* Search the titles first. *)
462 "select url, title, last_modified_date,
463 (lower (title) = lower ($search_terms)) as exact
465 where hostid = $hostid
468 and title_description_fti @@ to_tsquery ('default', $tsquery)
469 order by exact desc, last_modified_date desc, title" in
473 | (Some url, title, last_modified, _) ->
474 url, title, last_modified
475 | _ -> assert false) rows in
477 let have_titles = titles <> [] in
478 t#conditional "have_titles" have_titles;
480 (* Search the contents. *)
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
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
495 | (contentid, Some url, title, last_modified) ->
496 contentid, url, title, last_modified
497 | _ -> assert false) rows in
499 let have_contents = contents <> [] in
500 t#conditional "have_contents" have_contents;
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.
507 if contents = [] then []
511 List.map (fun (contentid, _,_,_) -> contentid) contents in
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
519 (* Generate the final tables. *)
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 ]
527 t#table "titles" table;
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
536 | Some sectionname -> true, sectionname in
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 ]
551 t#table "contents" table;
553 (* Do we have any results? *)
554 let have_results = have_titles || have_contents in
556 t#conditional "have_results" have_results;
558 (* Deliver the rest of the page. *)
559 ignore (print_string r t#to_string)
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.
567 let fetch_page page version allow_redirect =
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
575 where hostid = $hostid and lower (url) = lower ($page)" in
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,
585 | [_, Some redirect, _, _, _, _, _, _, _] ->
586 FPInternalRedirect redirect
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
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,
604 let rows = PGSQL(dbh)
605 "select id, title, description, keywords, last_modified_date,
606 css is not null, noodp
608 where hostid = $hostid and id = $version and
609 (url = $page or url_deleted = $page)" in
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,
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 =
624 not (q#param_true "no_redirect"),
625 try Some (Int32.of_string (q#param "version")) with Not_found -> None
629 let rec loop page' i =
630 if i > max_redirect then (
631 error ~title:"Too many redirections" ~back_button:true
633 ("Too many redirects between pages. This may happen because " ^
634 "of a cycle of redirections.");
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' ->
647 | FPExternalRedirect page' ->
648 (* This normally happens when a user has requested an uppercase
649 * page name. We redirect to the true (lowercase) version.
651 q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
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 ->
658 make_page title None None None
659 "Now" false None None page page'
667 register_script ~restrict:[CanView] run