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.50 2006/08/03 13:33:15 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
39 type fp_status = FPOK of int32 * string * string * Calendar.t * bool
40 | FPInternalRedirect of string
41 | FPExternalRedirect of string
44 (* Referer strings which help us decide if the user came from
45 * a search engine and highlight terms in the page appropriately.
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" ]
52 let split_words = Pcre.regexp "\\W+"
54 let split_qs_re = Pcre.regexp "\\?"
56 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
58 let run r (q : cgi) dbh hostid
59 ({ edit_anon = edit_anon; view_anon = view_anon } as host)
61 let page = q#param "page" in
62 let page = if page = "" then "index" else page in
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
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
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
81 (* Host-specific fields. *)
83 "select css is not null, feedback_email is not null, mailing_list, navigation
84 from hosts where id = $hostid" in
85 let has_host_css, has_feedback_email, mailing_list, navigation =
87 | [Some has_host_css, Some has_feedback_email,
88 mailing_list, navigation] ->
89 has_host_css, has_feedback_email, mailing_list, navigation
90 | _ -> assert false in
92 (* User permissions. *)
93 let can_edit = can_edit host user in
94 let can_manage_users = can_manage_users host user in
96 (* Do we have a stats page set up? *)
97 let has_stats = server_settings_stats_page dbh <> None in
99 (* Given the referer string, return the list of search terms. If none
100 * can be found, then throws Not_found.
102 let search_terms_from_referer referer =
104 List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
106 match Pcre.split ~rex:split_qs_re ~max:2 referer with
107 | [url] | [url;""] -> url, ""
108 | [url;qs] -> url, qs
109 | _ -> assert false in
110 let args = Cgi_args.parse qs in
112 List.find (fun argname -> List.mem_assoc argname args) argnames in
113 let search_string = List.assoc argname args in
114 Pcre.split ~rex:split_words search_string
117 (* Given a full page of XHTML, highlight search terms found in the
118 * <body> part of the page.
120 let highlight_search_terms xhtml search_terms span_class =
121 (* Split the original XHTML into strings and tags. For example if
122 * the original string is: "This is some <b>bold</b> text.<br/>", then
123 * after this step we will have the following list:
124 * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
126 let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
127 let xhtml = Array.to_list xhtml in
128 let xhtml = List.map (fun matches -> matches.(0)) xhtml in
130 (* Find the <body> ... </body> tags. We only want to apply
131 * highlighting to tags within this area.
133 let rec list_split f acc = function
134 | [] -> List.rev acc, []
135 | ((x :: _) as xs) when f x -> List.rev acc, xs
137 let acc = x :: acc in
141 list_split (fun str -> String.starts_with str "<body") [] xhtml in
143 list_split ((=) "</body>") [] body in
144 (* NB: Hopefully, xhtml = head @ body @ tail. *)
146 (* The search terms are a list of simple words. Turn into a big
147 * regular expression, because we want to substitute for each. We
148 * end up with a regexp like '(word1|word2|word3)'.
151 Pcre.regexp ~flags:[`CASELESS]
152 ("(" ^ String.concat "|" search_terms ^ ")") in
154 (* Do the substitution, but only on text, not elements! *)
157 "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
160 if String.length str > 0 && str.[0] != '<' then
161 Pcre.substitute ~rex ~subst str
165 (* Join the XHTML fragments back together again. *)
166 String.concat "" (List.concat [ head ; body ; tail ])
169 (* Check the templates table for extensions. *)
170 let get_extension url =
174 PGSQL(dbh) "select extension from templates
175 where $url ~ url_regexp
179 Some (List.assoc name !extensions)
181 Not_found | ExtList.List.Empty_list | Failure "hd" -> None
184 (* This code generates ordinary pages. *)
185 let make_page title description pageid last_modified_date has_page_css
186 version page page' extension =
187 let t = template_page in
188 let th = template_page_header in
190 th#set "title" title;
191 t#set "last_modified_date" last_modified_date;
193 (match description with
194 None -> th#conditional "has_description" false
195 | Some description ->
196 th#conditional "has_description" true;
197 th#set "description" description);
199 if page <> page' then (* redirection *) (
202 t#set "original_page" page; (* XXX title - get it from database *)
203 t#conditional "redirected" true
207 t#conditional "redirected" false
210 th#conditional "has_host_css" has_host_css;
211 th#conditional "has_page_css" has_page_css;
213 (* Are we showing an old version of the page? If so, warn. *)
216 t#conditional "is_old_version" false;
217 th#conditional "is_old_version" false
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));
224 (* Just before we show the header, call any registered pre-page
225 * handlers. They might want to send cookies.
227 List.iter (fun handler ->
228 handler r q dbh hostid page') !pre_page_handlers;
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.
235 ignore (print_string r th#to_string);
236 ignore (Request.rflush r);
238 t#conditional "has_feedback_email" has_feedback_email;
239 t#conditional "mailing_list" mailing_list;
240 t#conditional "navigation" navigation;
242 t#conditional "can_edit" can_edit;
243 t#conditional "can_manage_users" can_manage_users;
244 t#conditional "has_stats" has_stats;
246 (* Pull out the sections in this page. *)
251 let rows = PGSQL(dbh)
252 "select ordering, sectionname, content, divname, jsgo
253 from contents where pageid = $pageid order by ordering" in
256 (fun (ordering, sectionname, content, divname, jsgo) ->
257 let divname, has_divname =
260 | Some divname -> divname, true in
264 | Some jsgo -> jsgo, true in
265 let sectionname, has_sectionname =
266 match sectionname with
268 | Some sectionname -> sectionname, true in
269 let linkname = linkname_of_sectionname sectionname in
270 [ "ordering", Template.VarString (Int32.to_string ordering);
272 Template.VarConditional has_sectionname;
273 "sectionname", Template.VarString sectionname;
274 "linkname", Template.VarString linkname;
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
283 (* Call an extension to generate the first section in this page? *)
288 let content = extension r dbh hostid page' in
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 "";
299 section :: sections in
301 t#table "sections" sections;
306 t#conditional "user_logged_in" false
307 | User (_, username, _, _) ->
308 t#conditional "user_logged_in" true;
309 t#set "username" username);
311 (* Can anonymous users create accounts? If not them we don't
312 * want to offer to create accounts for them.
314 t#conditional "create_account_anon" host.create_account_anon;
316 (* If logged in, we want to update the recently_visited table. *)
317 if pageid <> None then (
319 | User (userid, _, _, _) ->
321 "delete from recently_visited
322 where hostid = $hostid and userid = $userid and url = $page'";
324 "insert into recently_visited (hostid, userid, url)
325 values ($hostid, $userid, $page')";
327 PGOCaml.begin_work dbh;
331 (* Navigation links. *)
333 let max_links = 18 in (* Show no more links than this. *)
335 (* What links here. *)
336 let wlh = what_links_here dbh hostid page' in
337 let wlh = List.take max_links wlh in
338 let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
342 | User (userid, _, _, _) ->
343 (* Recently visited URLs, but don't repeat any from the 'what
344 * links here' section, and don't link to self.
346 let not_urls = page' :: wlh_urls in
347 let limit = Int32.of_int (max_links - List.length wlh_urls) in
350 "select rv.url, p.title, rv.visit_time
351 from recently_visited rv, pages p
352 where rv.hostid = $hostid and rv.userid = $userid
353 and rv.url not in $@not_urls
354 and rv.hostid = p.hostid and rv.url = p.url
358 fun (url, title, _) -> url, title
363 let f (page, title) = [ "page", Template.VarString page;
364 "title", Template.VarString title ] in
365 let table = List.map f wlh in
366 t#table "what_links_here" table;
367 t#conditional "has_what_links_here" (wlh <> []);
369 let table = List.map f rv in
370 t#table "recently_visited" table;
371 t#conditional "has_recently_visited" (rv <> []);
373 (* If both lists are empty (ie. an empty navigation box would
374 * appear), then disable navigation altogether.
376 if wlh = [] && rv = [] then t#conditional "navigation" false
379 (* If we are coming from a search engine then we want to highlight
380 * search terms throughout the whole page ...
383 let referer = Table.get (Request.headers_in r) "Referer" in
384 let search_terms = search_terms_from_referer referer in
386 (* Highlight the search terms. *)
387 let xhtml = t#to_string in
388 let xhtml = highlight_search_terms xhtml search_terms "search_term" in
390 (* Deliver the page. *)
391 ignore (print_string r xhtml)
394 (* No referer / no search terms / not a search engine referer. *)
395 ignore (print_string r t#to_string)
398 (* This code generates 404 pages. *)
400 Request.set_status r 404; (* Return a 404 error code. *)
402 let th = template_404_header in
408 ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
411 th#set "search_terms" search_terms;
413 (* Flush out the header while we start the search. *)
415 ignore (print_string r th#to_string);
416 ignore (Request.rflush r);
418 let t = template_404 in
419 t#set "query" search_terms;
420 t#set "canonical_hostname" host.canonical_hostname;
422 (* This is a simplified version of the code in search.ml. *)
424 (* Get the keywords from the query string. *)
425 let keywords = Pcre.split ~rex:split_words search_terms in
427 List.filter (fun s -> not (string_is_whitespace s)) keywords in
428 let keywords = List.map String.lowercase keywords in
430 (* Turn the keywords into a tsearch2 ts_query string. *)
431 let tsquery = String.concat "&" keywords in
433 (* Search the titles first. *)
436 "select url, title, last_modified_date,
437 (lower (title) = lower ($search_terms)) as exact
439 where hostid = $hostid
442 and title_description_fti @@ to_tsquery ('default', $tsquery)
443 order by exact desc, last_modified_date desc, title" in
447 | (Some url, title, last_modified, _) ->
448 url, title, last_modified
449 | _ -> assert false) rows in
451 let have_titles = titles <> [] in
452 t#conditional "have_titles" have_titles;
454 (* Search the contents. *)
457 "select c.id, p.url, p.title, p.last_modified_date
458 from contents c, pages p
459 where c.pageid = p.id
460 and p.hostid = $hostid
462 and p.redirect is null
463 and c.content_fti @@ to_tsquery ('default', $tsquery)
464 order by p.last_modified_date desc, p.title
469 | (contentid, Some url, title, last_modified) ->
470 contentid, url, title, last_modified
471 | _ -> assert false) rows in
473 let have_contents = contents <> [] in
474 t#conditional "have_contents" have_contents;
476 (* Pull out the actual text which matched so we can generate a summary.
477 * XXX tsearch2 can actually do better than this by emboldening
478 * the text which maps.
481 if contents = [] then []
485 List.map (fun (contentid, _,_,_) -> contentid) contents in
487 "select id, sectionname, content from contents
488 where id in $@contentids" in
489 List.map (fun (id, sectionname, content) ->
490 id, (sectionname, content)) rows
493 (* Generate the final tables. *)
495 List.map (fun (url, title, last_modified) ->
496 let last_modified = printable_date last_modified in
497 [ "url", Template.VarString url;
498 "title", Template.VarString title;
499 "last_modified", Template.VarString last_modified ]
501 t#table "titles" table;
505 (fun (contentid, url, title, last_modified) ->
506 let sectionname, content = List.assoc contentid content_map in
507 let have_sectionname, sectionname =
508 match sectionname with
510 | Some sectionname -> true, sectionname in
513 (Wikilib.text_of_xhtml
514 (Wikilib.xhtml_of_content r dbh hostid content)) in
515 let linkname = linkname_of_sectionname sectionname in
516 let last_modified = printable_date last_modified in
517 [ "url", Template.VarString url;
518 "title", Template.VarString title;
519 "have_sectionname", Template.VarConditional have_sectionname;
520 "sectionname", Template.VarString sectionname;
521 "linkname", Template.VarString linkname;
522 "content", Template.VarString content;
523 "last_modified", Template.VarString last_modified ]
525 t#table "contents" table;
527 (* Do we have any results? *)
528 let have_results = have_titles || have_contents in
530 t#conditional "have_results" have_results;
532 (* Deliver the rest of the page. *)
533 ignore (print_string r t#to_string)
536 (* Fetch a page by name. This function can give three answers:
537 * (1) Page fetched OK (fetches some details of the page).
538 * (2) Page is a redirect (fetches the name of the redirect page).
539 * (3) Page not found in database, could be template or 404 error.
541 let fetch_page page version allow_redirect =
544 if allow_redirect then (
545 let rows = PGSQL(dbh)
546 "select url, redirect, id, title, description,
547 last_modified_date, css is not null
549 where hostid = $hostid and lower (url) = lower ($page)" in
551 | [Some page', _, _, _, _, _, _]
552 when page <> page' -> (* different case *)
553 FPExternalRedirect page'
554 | [ _, None, id, title, description,
555 last_modified_date, has_page_css ] ->
556 let has_page_css = Option.get has_page_css in
557 FPOK (id, title, description, last_modified_date,
559 | [_, Some redirect, _, _, _, _, _] ->
560 FPInternalRedirect redirect
563 ) else (* redirects not allowed ... *) (
564 let rows = PGSQL(dbh)
565 "select id, title, description, last_modified_date,
567 from pages where hostid = $hostid and url = $page" in
569 | [ id, title, description,
570 last_modified_date, has_page_css ] ->
571 let has_page_css = Option.get has_page_css in
572 FPOK (id, title, description, last_modified_date,
578 let rows = PGSQL(dbh)
579 "select id, title, description, last_modified_date,
582 where hostid = $hostid and id = $version and
583 (url = $page or url_deleted = $page)" in
585 | [ id, title, description,
586 last_modified_date, has_page_css ] ->
587 let has_page_css = Option.get has_page_css in
588 FPOK (id, title, description, last_modified_date,
594 (* Here we deal with the complex business of redirects and versions. *)
595 (* Only allow the no_redirect and version syntax for editors. *)
596 let allow_redirect, version =
598 not (q#param_true "no_redirect"),
599 try Some (Int32.of_string (q#param "version")) with Not_found -> None
603 let rec loop page' i =
604 if i > max_redirect then (
605 error ~title:"Too many redirections" ~back_button:true
607 ("Too many redirects between pages. This may happen because " ^
608 "of a cycle of redirections.");
611 match fetch_page page' version allow_redirect with
612 | FPOK (pageid, title, description, last_modified_date, has_page_css)->
613 (* Check if the page is also a template. *)
614 let extension = get_extension page' in
615 make_page title (Some description) (Some pageid)
616 (printable_date last_modified_date) has_page_css
617 version page page' extension
618 | FPInternalRedirect page' ->
620 | FPExternalRedirect page' ->
621 (* This normally happens when a user has requested an uppercase
622 * page name. We redirect to the true (lowercase) version.
624 q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
626 (* Might be a templated page with no content in it. *)
627 let extension = get_extension page' in
628 (match extension with
629 | (Some _) as extension ->
631 make_page title None None
632 "Now" false None page page'
640 register_script ~restrict:[CanView] run