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.47 2006/07/26 13:19:49 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
37 type fp_status = FPOK of int32 * string * string * Calendar.t * bool
38 | FPInternalRedirect of string
39 | FPExternalRedirect of string
42 (* Referer strings which help us decide if the user came from
43 * a search engine and highlight terms in the page appropriately.
45 let search_engines = [
46 Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
47 Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
48 Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
50 let split_words = Pcre.regexp "\\W+"
52 let split_qs_re = Pcre.regexp "\\?"
54 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
56 let run r (q : cgi) dbh hostid
57 ({ edit_anon = edit_anon; view_anon = view_anon } as host)
59 let page = q#param "page" in
60 let page = if page = "" then "index" else page in
62 (* The main "page" template is split in two to improve the speed of
63 * delivery of the page. The very first part ("page_header.html")
64 * contains the page <head>, crucially including all the links to the
65 * stylesheets. We send this first and flush it out to the client so
66 * that the client can begin requesting stylesheets, background images
67 * and so on. After this we compose the main page ("page.html") and
71 let template_page_header =
72 get_template ~page dbh hostid "page_header.html" in
73 let template_page = get_template ~page dbh hostid "page.html" in
75 (* This is the simpler template for 404 pages. *)
76 let template_404 = get_template dbh hostid "page_404.html" in
78 (* Host-specific fields. *)
80 "select css is not null, feedback_email is not null, mailing_list, navigation
81 from hosts where id = $hostid" in
82 let has_host_css, has_feedback_email, mailing_list, navigation =
84 | [Some has_host_css, Some has_feedback_email,
85 mailing_list, navigation] ->
86 has_host_css, has_feedback_email, mailing_list, navigation
87 | _ -> assert false in
89 (* User permissions. *)
90 let can_edit = can_edit host user in
91 let can_manage_users = can_manage_users host user in
93 (* Do we have a stats page set up? *)
94 let has_stats = server_settings_stats_page dbh <> None in
96 (* Given the referer string, return the list of search terms. If none
97 * can be found, then throws Not_found.
99 let search_terms_from_referer referer =
101 List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
103 match Pcre.split ~rex:split_qs_re ~max:2 referer with
104 | [url] | [url;""] -> url, ""
105 | [url;qs] -> url, qs
106 | _ -> assert false in
107 let args = Cgi_args.parse qs in
109 List.find (fun argname -> List.mem_assoc argname args) argnames in
110 let search_string = List.assoc argname args in
111 Pcre.split ~rex:split_words search_string
114 (* Given a full page of XHTML, highlight search terms found in the
115 * <body> part of the page.
117 let highlight_search_terms xhtml search_terms span_class =
118 (* Split the original XHTML into strings and tags. For example if
119 * the original string is: "This is some <b>bold</b> text.<br/>", then
120 * after this step we will have the following list:
121 * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
123 let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
124 let xhtml = Array.to_list xhtml in
125 let xhtml = List.map (fun matches -> matches.(0)) xhtml in
127 (* Find the <body> ... </body> tags. We only want to apply
128 * highlighting to tags within this area.
130 let rec list_split f acc = function
131 | [] -> List.rev acc, []
132 | ((x :: _) as xs) when f x -> List.rev acc, xs
134 let acc = x :: acc in
138 list_split (fun str -> String.starts_with str "<body") [] xhtml in
140 list_split ((=) "</body>") [] body in
141 (* NB: Hopefully, xhtml = head @ body @ tail. *)
143 (* The search terms are a list of simple words. Turn into a big
144 * regular expression, because we want to substitute for each. We
145 * end up with a regexp like '(word1|word2|word3)'.
148 Pcre.regexp ~flags:[`CASELESS]
149 ("(" ^ String.concat "|" search_terms ^ ")") in
151 (* Do the substitution, but only on text, not elements! *)
154 "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
157 if String.length str > 0 && str.[0] != '<' then
158 Pcre.substitute ~rex ~subst str
162 (* Join the XHTML fragments back together again. *)
163 String.concat "" (List.concat [ head ; body ; tail ])
166 (* Check the templates table for extensions. *)
167 let get_extension url =
171 PGSQL(dbh) "select extension from templates
172 where $url ~ url_regexp
176 Some (List.assoc name !extensions)
178 Not_found | ExtList.List.Empty_list -> None
181 (* This code generates ordinary pages. *)
182 let make_page title description pageid last_modified_date has_page_css
183 version page page' extension =
184 let t = template_page in
185 let th = template_page_header in
187 th#set "title" title;
188 t#set "last_modified_date" last_modified_date;
190 (match description with
191 None -> th#conditional "has_description" false
192 | Some description ->
193 th#conditional "has_description" true;
194 th#set "description" description);
196 if page <> page' then (* redirection *) (
199 t#set "original_page" page; (* XXX title - get it from database *)
200 t#conditional "redirected" true
204 t#conditional "redirected" false
207 th#conditional "has_host_css" has_host_css;
208 th#conditional "has_page_css" has_page_css;
210 (* Are we showing an old version of the page? If so, warn. *)
213 t#conditional "is_old_version" false;
214 th#conditional "is_old_version" false
216 t#conditional "is_old_version" true;
217 th#conditional "is_old_version" true;
218 t#set "old_version" (Int32.to_string pageid);
219 th#set "old_version" (Int32.to_string pageid));
221 (* At this point, we can print out the header and flush it back to
222 * the user, allowing the browser to start fetching stylesheets
223 * and background images while we compose the page.
226 ignore (print_string r th#to_string);
227 ignore (Request.rflush r);
229 t#conditional "has_feedback_email" has_feedback_email;
230 t#conditional "mailing_list" mailing_list;
231 t#conditional "navigation" navigation;
233 t#conditional "can_edit" can_edit;
234 t#conditional "can_manage_users" can_manage_users;
235 t#conditional "has_stats" has_stats;
237 (* Pull out the sections in this page. *)
242 let rows = PGSQL(dbh)
243 "select ordering, sectionname, content, divname, jsgo
244 from contents where pageid = $pageid order by ordering" in
247 (fun (ordering, sectionname, content, divname, jsgo) ->
248 let divname, has_divname =
251 | Some divname -> divname, true in
255 | Some jsgo -> jsgo, true in
256 let sectionname, has_sectionname =
257 match sectionname with
259 | Some sectionname -> sectionname, true in
260 let linkname = linkname_of_sectionname sectionname in
261 [ "ordering", Template.VarString (Int32.to_string ordering);
263 Template.VarConditional has_sectionname;
264 "sectionname", Template.VarString sectionname;
265 "linkname", Template.VarString linkname;
268 (Wikilib.xhtml_of_content dbh hostid content);
269 "has_divname", Template.VarConditional has_divname;
270 "divname", Template.VarString divname;
271 "has_jsgo", Template.VarConditional has_jsgo;
272 "jsgo", Template.VarString jsgo ]) rows in
274 (* Call an extension to generate the first section in this page? *)
279 let content = extension dbh hostid page' in
281 "ordering", Template.VarString "0";
282 "has_sectionname", Template.VarConditional false;
283 "linkname", Template.VarString "";
284 "content", Template.VarString content;
285 "has_divname", Template.VarConditional true;
286 "divname", Template.VarString "form_div";
287 "has_jsgo", Template.VarConditional false;
288 "jsgo", Template.VarString "";
290 section :: sections in
292 t#table "sections" sections;
297 t#conditional "user_logged_in" false
298 | User (_, username, _, _) ->
299 t#conditional "user_logged_in" true;
300 t#set "username" username);
302 (* Can anonymous users create accounts? If not them we don't
303 * want to offer to create accounts for them.
305 t#conditional "create_account_anon" host.create_account_anon;
307 (* If logged in, we want to update the recently_visited table. *)
308 if pageid <> None then (
310 | User (userid, _, _, _) ->
312 "delete from recently_visited
313 where hostid = $hostid and userid = $userid and url = $page'";
315 "insert into recently_visited (hostid, userid, url)
316 values ($hostid, $userid, $page')";
318 PGOCaml.begin_work dbh;
322 (* Navigation links. *)
324 let max_links = 18 in (* Show no more links than this. *)
326 (* What links here. *)
327 let wlh = what_links_here dbh hostid page' in
328 let wlh = List.take max_links wlh in
329 let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
333 | User (userid, _, _, _) ->
334 (* Recently visited URLs, but don't repeat any from the 'what
335 * links here' section, and don't link to self.
337 let not_urls = page' :: wlh_urls in
338 let limit = Int32.of_int (max_links - List.length wlh_urls) in
341 "select rv.url, p.title, rv.visit_time
342 from recently_visited rv, pages p
343 where rv.hostid = $hostid and rv.userid = $userid
344 and rv.url not in $@not_urls
345 and rv.hostid = p.hostid and rv.url = p.url
349 fun (url, title, _) -> url, title
354 let f (page, title) = [ "page", Template.VarString page;
355 "title", Template.VarString title ] in
356 let table = List.map f wlh in
357 t#table "what_links_here" table;
358 t#conditional "has_what_links_here" (wlh <> []);
360 let table = List.map f rv in
361 t#table "recently_visited" table;
362 t#conditional "has_recently_visited" (rv <> []);
364 (* If both lists are empty (ie. an empty navigation box would
365 * appear), then disable navigation altogether.
367 if wlh = [] && rv = [] then t#conditional "navigation" false
370 (* If we are coming from a search engine then we want to highlight
371 * search terms throughout the whole page ...
374 let referer = Table.get (Request.headers_in r) "Referer" in
375 let search_terms = search_terms_from_referer referer in
377 (* Highlight the search terms. *)
378 let xhtml = t#to_string in
379 let xhtml = highlight_search_terms xhtml search_terms "search_term" in
381 (* Deliver the page. *)
382 ignore (print_string r xhtml)
385 (* No referer / no search terms / not a search engine referer. *)
386 ignore (print_string r t#to_string)
389 (* This code generates 404 pages. *)
391 Request.set_status r 404; (* Return a 404 error code. *)
393 let t = template_404 in
399 ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
402 t#set "search_terms" search_terms;
404 t#conditional "can_edit" can_edit;
405 t#conditional "can_manage_users" can_manage_users;
406 t#conditional "has_stats" has_stats;
411 (* Fetch a page by name. This function can give three answers:
412 * (1) Page fetched OK (fetches some details of the page).
413 * (2) Page is a redirect (fetches the name of the redirect page).
414 * (3) Page not found in database, could be template or 404 error.
416 let fetch_page page version allow_redirect =
419 if allow_redirect then (
420 let rows = PGSQL(dbh)
421 "select url, redirect, id, title, description,
422 last_modified_date, css is not null
424 where hostid = $hostid and lower (url) = lower ($page)" in
426 | [Some page', _, _, _, _, _, _]
427 when page <> page' -> (* different case *)
428 FPExternalRedirect page'
429 | [ _, None, id, title, description,
430 last_modified_date, has_page_css ] ->
431 let has_page_css = Option.get has_page_css in
432 FPOK (id, title, description, last_modified_date,
434 | [_, Some redirect, _, _, _, _, _] ->
435 FPInternalRedirect redirect
438 ) else (* redirects not allowed ... *) (
439 let rows = PGSQL(dbh)
440 "select id, title, description, last_modified_date,
442 from pages where hostid = $hostid and url = $page" in
444 | [ id, title, description,
445 last_modified_date, has_page_css ] ->
446 let has_page_css = Option.get has_page_css in
447 FPOK (id, title, description, last_modified_date,
453 let rows = PGSQL(dbh)
454 "select id, title, description, last_modified_date,
457 where hostid = $hostid and id = $version and
458 (url = $page or url_deleted = $page)" in
460 | [ id, title, description,
461 last_modified_date, has_page_css ] ->
462 let has_page_css = Option.get has_page_css in
463 FPOK (id, title, description, last_modified_date,
469 (* Here we deal with the complex business of redirects and versions. *)
470 (* Only allow the no_redirect and version syntax for editors. *)
471 let allow_redirect, version =
473 not (q#param_true "no_redirect"),
474 try Some (Int32.of_string (q#param "version")) with Not_found -> None
478 let rec loop page' i =
479 if i > max_redirect then (
480 error ~title:"Too many redirections" ~back_button:true
482 ("Too many redirects between pages. This may happen because " ^
483 "of a cycle of redirections.");
486 match fetch_page page' version allow_redirect with
487 | FPOK (pageid, title, description, last_modified_date, has_page_css)->
488 (* Check if the page is also a template. *)
489 let extension = get_extension page' in
490 make_page title (Some description) (Some pageid)
491 (printable_date last_modified_date) has_page_css
492 version page page' extension
493 | FPInternalRedirect page' ->
495 | FPExternalRedirect page' ->
496 (* This normally happens when a user has requested an uppercase
497 * page name. We redirect to the true (lowercase) version.
499 q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
501 (* Might be a templated page with no content in it. *)
502 let extension = get_extension page' in
503 (match extension with
504 | (Some _) as extension ->
506 make_page title None None
507 "Now" false None page page'
515 register_script ~restrict:[CanView] run