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.49 2006/08/01 14:50:47 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
38 type fp_status = FPOK of int32 * string * string * Calendar.t * bool
39 | FPInternalRedirect of string
40 | FPExternalRedirect of string
43 (* Referer strings which help us decide if the user came from
44 * a search engine and highlight terms in the page appropriately.
46 let search_engines = [
47 Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
48 Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
49 Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
51 let split_words = Pcre.regexp "\\W+"
53 let split_qs_re = Pcre.regexp "\\?"
55 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
57 let run r (q : cgi) dbh hostid
58 ({ edit_anon = edit_anon; view_anon = view_anon } as host)
60 let page = q#param "page" in
61 let page = if page = "" then "index" else page in
63 (* The main "page" template is split in two to improve the speed of
64 * delivery of the page. The very first part ("page_header.html")
65 * contains the page <head>, crucially including all the links to the
66 * stylesheets. We send this first and flush it out to the client so
67 * that the client can begin requesting stylesheets, background images
68 * and so on. After this we compose the main page ("page.html") and
72 let template_page_header =
73 get_template ~page dbh hostid "page_header.html" in
74 let template_page = get_template ~page dbh hostid "page.html" in
76 (* This is the simpler template for 404 pages. *)
77 let template_404 = get_template dbh hostid "page_404.html" in
79 (* Host-specific fields. *)
81 "select css is not null, feedback_email is not null, mailing_list, navigation
82 from hosts where id = $hostid" in
83 let has_host_css, has_feedback_email, mailing_list, navigation =
85 | [Some has_host_css, Some has_feedback_email,
86 mailing_list, navigation] ->
87 has_host_css, has_feedback_email, mailing_list, navigation
88 | _ -> assert false in
90 (* User permissions. *)
91 let can_edit = can_edit host user in
92 let can_manage_users = can_manage_users host user in
94 (* Do we have a stats page set up? *)
95 let has_stats = server_settings_stats_page dbh <> None in
97 (* Given the referer string, return the list of search terms. If none
98 * can be found, then throws Not_found.
100 let search_terms_from_referer referer =
102 List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
104 match Pcre.split ~rex:split_qs_re ~max:2 referer with
105 | [url] | [url;""] -> url, ""
106 | [url;qs] -> url, qs
107 | _ -> assert false in
108 let args = Cgi_args.parse qs in
110 List.find (fun argname -> List.mem_assoc argname args) argnames in
111 let search_string = List.assoc argname args in
112 Pcre.split ~rex:split_words search_string
115 (* Given a full page of XHTML, highlight search terms found in the
116 * <body> part of the page.
118 let highlight_search_terms xhtml search_terms span_class =
119 (* Split the original XHTML into strings and tags. For example if
120 * the original string is: "This is some <b>bold</b> text.<br/>", then
121 * after this step we will have the following list:
122 * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
124 let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
125 let xhtml = Array.to_list xhtml in
126 let xhtml = List.map (fun matches -> matches.(0)) xhtml in
128 (* Find the <body> ... </body> tags. We only want to apply
129 * highlighting to tags within this area.
131 let rec list_split f acc = function
132 | [] -> List.rev acc, []
133 | ((x :: _) as xs) when f x -> List.rev acc, xs
135 let acc = x :: acc in
139 list_split (fun str -> String.starts_with str "<body") [] xhtml in
141 list_split ((=) "</body>") [] body in
142 (* NB: Hopefully, xhtml = head @ body @ tail. *)
144 (* The search terms are a list of simple words. Turn into a big
145 * regular expression, because we want to substitute for each. We
146 * end up with a regexp like '(word1|word2|word3)'.
149 Pcre.regexp ~flags:[`CASELESS]
150 ("(" ^ String.concat "|" search_terms ^ ")") in
152 (* Do the substitution, but only on text, not elements! *)
155 "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
158 if String.length str > 0 && str.[0] != '<' then
159 Pcre.substitute ~rex ~subst str
163 (* Join the XHTML fragments back together again. *)
164 String.concat "" (List.concat [ head ; body ; tail ])
167 (* Check the templates table for extensions. *)
168 let get_extension url =
172 PGSQL(dbh) "select extension from templates
173 where $url ~ url_regexp
177 Some (List.assoc name !extensions)
179 Not_found | ExtList.List.Empty_list | Failure "hd" -> None
182 (* This code generates ordinary pages. *)
183 let make_page title description pageid last_modified_date has_page_css
184 version page page' extension =
185 let t = template_page in
186 let th = template_page_header in
188 th#set "title" title;
189 t#set "last_modified_date" last_modified_date;
191 (match description with
192 None -> th#conditional "has_description" false
193 | Some description ->
194 th#conditional "has_description" true;
195 th#set "description" description);
197 if page <> page' then (* redirection *) (
200 t#set "original_page" page; (* XXX title - get it from database *)
201 t#conditional "redirected" true
205 t#conditional "redirected" false
208 th#conditional "has_host_css" has_host_css;
209 th#conditional "has_page_css" has_page_css;
211 (* Are we showing an old version of the page? If so, warn. *)
214 t#conditional "is_old_version" false;
215 th#conditional "is_old_version" false
217 t#conditional "is_old_version" true;
218 th#conditional "is_old_version" true;
219 t#set "old_version" (Int32.to_string pageid);
220 th#set "old_version" (Int32.to_string pageid));
222 (* Just before we show the header, call any registered pre-page
223 * handlers. They might want to send cookies.
225 List.iter (fun handler ->
226 handler r q dbh hostid page') !pre_page_handlers;
228 (* At this point, we can print out the header and flush it back to
229 * the user, allowing the browser to start fetching stylesheets
230 * and background images while we compose the page.
233 ignore (print_string r th#to_string);
234 ignore (Request.rflush r);
236 t#conditional "has_feedback_email" has_feedback_email;
237 t#conditional "mailing_list" mailing_list;
238 t#conditional "navigation" navigation;
240 t#conditional "can_edit" can_edit;
241 t#conditional "can_manage_users" can_manage_users;
242 t#conditional "has_stats" has_stats;
244 (* Pull out the sections in this page. *)
249 let rows = PGSQL(dbh)
250 "select ordering, sectionname, content, divname, jsgo
251 from contents where pageid = $pageid order by ordering" in
254 (fun (ordering, sectionname, content, divname, jsgo) ->
255 let divname, has_divname =
258 | Some divname -> divname, true in
262 | Some jsgo -> jsgo, true in
263 let sectionname, has_sectionname =
264 match sectionname with
266 | Some sectionname -> sectionname, true in
267 let linkname = linkname_of_sectionname sectionname in
268 [ "ordering", Template.VarString (Int32.to_string ordering);
270 Template.VarConditional has_sectionname;
271 "sectionname", Template.VarString sectionname;
272 "linkname", Template.VarString linkname;
275 (Wikilib.xhtml_of_content r dbh hostid content);
276 "has_divname", Template.VarConditional has_divname;
277 "divname", Template.VarString divname;
278 "has_jsgo", Template.VarConditional has_jsgo;
279 "jsgo", Template.VarString jsgo ]) rows in
281 (* Call an extension to generate the first section in this page? *)
286 let content = extension r dbh hostid page' in
288 "ordering", Template.VarString "0";
289 "has_sectionname", Template.VarConditional false;
290 "linkname", Template.VarString "";
291 "content", Template.VarString content;
292 "has_divname", Template.VarConditional true;
293 "divname", Template.VarString "form_div";
294 "has_jsgo", Template.VarConditional false;
295 "jsgo", Template.VarString "";
297 section :: sections in
299 t#table "sections" sections;
304 t#conditional "user_logged_in" false
305 | User (_, username, _, _) ->
306 t#conditional "user_logged_in" true;
307 t#set "username" username);
309 (* Can anonymous users create accounts? If not them we don't
310 * want to offer to create accounts for them.
312 t#conditional "create_account_anon" host.create_account_anon;
314 (* If logged in, we want to update the recently_visited table. *)
315 if pageid <> None then (
317 | User (userid, _, _, _) ->
319 "delete from recently_visited
320 where hostid = $hostid and userid = $userid and url = $page'";
322 "insert into recently_visited (hostid, userid, url)
323 values ($hostid, $userid, $page')";
325 PGOCaml.begin_work dbh;
329 (* Navigation links. *)
331 let max_links = 18 in (* Show no more links than this. *)
333 (* What links here. *)
334 let wlh = what_links_here dbh hostid page' in
335 let wlh = List.take max_links wlh in
336 let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
340 | User (userid, _, _, _) ->
341 (* Recently visited URLs, but don't repeat any from the 'what
342 * links here' section, and don't link to self.
344 let not_urls = page' :: wlh_urls in
345 let limit = Int32.of_int (max_links - List.length wlh_urls) in
348 "select rv.url, p.title, rv.visit_time
349 from recently_visited rv, pages p
350 where rv.hostid = $hostid and rv.userid = $userid
351 and rv.url not in $@not_urls
352 and rv.hostid = p.hostid and rv.url = p.url
356 fun (url, title, _) -> url, title
361 let f (page, title) = [ "page", Template.VarString page;
362 "title", Template.VarString title ] in
363 let table = List.map f wlh in
364 t#table "what_links_here" table;
365 t#conditional "has_what_links_here" (wlh <> []);
367 let table = List.map f rv in
368 t#table "recently_visited" table;
369 t#conditional "has_recently_visited" (rv <> []);
371 (* If both lists are empty (ie. an empty navigation box would
372 * appear), then disable navigation altogether.
374 if wlh = [] && rv = [] then t#conditional "navigation" false
377 (* If we are coming from a search engine then we want to highlight
378 * search terms throughout the whole page ...
381 let referer = Table.get (Request.headers_in r) "Referer" in
382 let search_terms = search_terms_from_referer referer in
384 (* Highlight the search terms. *)
385 let xhtml = t#to_string in
386 let xhtml = highlight_search_terms xhtml search_terms "search_term" in
388 (* Deliver the page. *)
389 ignore (print_string r xhtml)
392 (* No referer / no search terms / not a search engine referer. *)
393 ignore (print_string r t#to_string)
396 (* This code generates 404 pages. *)
398 Request.set_status r 404; (* Return a 404 error code. *)
400 let t = template_404 in
406 ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
409 t#set "search_terms" search_terms;
411 t#conditional "can_edit" can_edit;
412 t#conditional "can_manage_users" can_manage_users;
413 t#conditional "has_stats" has_stats;
418 (* Fetch a page by name. This function can give three answers:
419 * (1) Page fetched OK (fetches some details of the page).
420 * (2) Page is a redirect (fetches the name of the redirect page).
421 * (3) Page not found in database, could be template or 404 error.
423 let fetch_page page version allow_redirect =
426 if allow_redirect then (
427 let rows = PGSQL(dbh)
428 "select url, redirect, id, title, description,
429 last_modified_date, css is not null
431 where hostid = $hostid and lower (url) = lower ($page)" in
433 | [Some page', _, _, _, _, _, _]
434 when page <> page' -> (* different case *)
435 FPExternalRedirect page'
436 | [ _, None, id, title, description,
437 last_modified_date, has_page_css ] ->
438 let has_page_css = Option.get has_page_css in
439 FPOK (id, title, description, last_modified_date,
441 | [_, Some redirect, _, _, _, _, _] ->
442 FPInternalRedirect redirect
445 ) else (* redirects not allowed ... *) (
446 let rows = PGSQL(dbh)
447 "select id, title, description, last_modified_date,
449 from pages where hostid = $hostid and url = $page" in
451 | [ id, title, description,
452 last_modified_date, has_page_css ] ->
453 let has_page_css = Option.get has_page_css in
454 FPOK (id, title, description, last_modified_date,
460 let rows = PGSQL(dbh)
461 "select id, title, description, last_modified_date,
464 where hostid = $hostid and id = $version and
465 (url = $page or url_deleted = $page)" in
467 | [ id, title, description,
468 last_modified_date, has_page_css ] ->
469 let has_page_css = Option.get has_page_css in
470 FPOK (id, title, description, last_modified_date,
476 (* Here we deal with the complex business of redirects and versions. *)
477 (* Only allow the no_redirect and version syntax for editors. *)
478 let allow_redirect, version =
480 not (q#param_true "no_redirect"),
481 try Some (Int32.of_string (q#param "version")) with Not_found -> None
485 let rec loop page' i =
486 if i > max_redirect then (
487 error ~title:"Too many redirections" ~back_button:true
489 ("Too many redirects between pages. This may happen because " ^
490 "of a cycle of redirections.");
493 match fetch_page page' version allow_redirect with
494 | FPOK (pageid, title, description, last_modified_date, has_page_css)->
495 (* Check if the page is also a template. *)
496 let extension = get_extension page' in
497 make_page title (Some description) (Some pageid)
498 (printable_date last_modified_date) has_page_css
499 version page page' extension
500 | FPInternalRedirect page' ->
502 | FPExternalRedirect page' ->
503 (* This normally happens when a user has requested an uppercase
504 * page name. We redirect to the true (lowercase) version.
506 q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
508 (* Might be a templated page with no content in it. *)
509 let extension = get_extension page' in
510 (match extension with
511 | (Some _) as extension ->
513 make_page title None None
514 "Now" false None page page'
522 register_script ~restrict:[CanView] run