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.39 2004/11/05 11:35:53 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 int * string * string * Dbi.datetime * bool
38 | FPRedirect of string
41 (* Referer strings which help us decide if the user came from
42 * a search engine and highlight terms in the page appropriately.
44 let search_engines = [
45 Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
46 Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
47 Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
49 let split_words = Pcre.regexp "\\W+"
51 let split_qs_re = Pcre.regexp "\\?"
53 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
55 let run r (q : cgi) (dbh : Dbi.connection) hostid
56 ({ edit_anon = edit_anon;
57 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. *)
79 let sth = dbh#prepare_cached "select css is not null,
80 feedback_email is not null,
81 mailing_list, navigation
82 from hosts where id = ?" in
83 sth#execute [`Int hostid];
84 let has_host_css, has_feedback_email, mailing_list, navigation =
85 match sth#fetch1 () with
86 | [ `Bool has_host_css; `Bool has_feedback_email; `Bool mailing_list;
88 has_host_css, has_feedback_email, mailing_list, navigation
89 | _ -> assert false in
91 (* User permissions. *)
92 let can_edit = can_edit host user in
93 let can_manage_users = can_manage_users host user in
95 (* Do we have a stats page set up? *)
96 let has_stats = server_settings_stats_page dbh <> None in
98 (* Given the referer string, return the list of search terms. If none
99 * can be found, then throws Not_found.
101 let search_terms_from_referer referer =
103 List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
105 match Pcre.split ~rex:split_qs_re ~max:2 referer with
106 | [url] | [url;""] -> url, ""
107 | [url;qs] -> url, qs
108 | _ -> assert false in
109 let args = Cgi_args.parse qs in
111 List.find (fun argname -> List.mem_assoc argname args) argnames in
112 let search_string = List.assoc argname args in
113 Pcre.split ~rex:split_words search_string
116 (* Given a full page of XHTML, highlight search terms found in the
117 * <body> part of the page.
119 let highlight_search_terms xhtml search_terms span_class =
120 (* Split the original XHTML into strings and tags. For example if
121 * the original string is: "This is some <b>bold</b> text.<br/>", then
122 * after this step we will have the following list:
123 * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
125 let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
126 let xhtml = Array.to_list xhtml in
127 let xhtml = List.map (fun matches -> matches.(0)) xhtml in
129 (* Find the <body> ... </body> tags. We only want to apply
130 * highlighting to tags within this area.
132 let rec list_split f acc = function
133 | [] -> List.rev acc, []
134 | ((x :: _) as xs) when f x -> List.rev acc, xs
136 let acc = x :: acc in
140 list_split (fun str -> String.starts_with str "<body") [] xhtml in
142 list_split ((=) "</body>") [] body in
143 (* NB: Hopefully, xhtml = head @ body @ tail. *)
145 (* The search terms are a list of simple words. Turn into a big
146 * regular expression, because we want to substitute for each. We
147 * end up with a regexp like '(word1|word2|word3)'.
150 Pcre.regexp ~flags:[`CASELESS]
151 ("(" ^ String.concat "|" search_terms ^ ")") in
153 (* Do the substitution, but only on text, not elements! *)
156 "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
159 if String.length str > 0 && str.[0] != '<' then
160 Pcre.substitute ~rex ~subst str
164 (* Join the XHTML fragments back together again. *)
165 String.concat "" (List.concat [ head ; body ; tail ])
168 (* Check the templates table for extensions. *)
169 let get_extension url =
170 let sth = dbh#prepare_cached "select extension from templates
174 sth#execute [`String url];
177 let name = sth#fetch1string () in
178 Some (List.assoc name !extensions)
183 (* This code generates ordinary pages. *)
184 let make_page title description pageid last_modified_date has_page_css
185 version page page' extension =
186 let t = template_page in
187 let th = template_page_header in
189 th#set "title" title;
190 t#set "last_modified_date" last_modified_date;
192 (match description with
193 None -> th#conditional "has_description" false
194 | Some description ->
195 th#conditional "has_description" true;
196 th#set "description" description);
198 if page <> page' then (* redirection *) (
201 t#set "original_page" page; (* XXX title - get it from database *)
202 t#conditional "redirected" true
206 t#conditional "redirected" false
209 th#conditional "has_host_css" has_host_css;
210 th#conditional "has_page_css" has_page_css;
212 (* Are we showing an old version of the page? If so, warn. *)
215 t#conditional "is_old_version" false;
216 th#conditional "is_old_version" false
218 t#conditional "is_old_version" true;
219 th#conditional "is_old_version" true;
220 t#set "old_version" (string_of_int pageid);
221 th#set "old_version" (string_of_int pageid));
223 (* At this point, we can print out the header and flush it back to
224 * the user, allowing the browser to start fetching stylesheets
225 * and background images while we compose the page.
228 print_string r th#to_string;
231 t#conditional "has_feedback_email" has_feedback_email;
232 t#conditional "mailing_list" mailing_list;
233 t#conditional "navigation" navigation;
235 t#conditional "can_edit" can_edit;
236 t#conditional "can_manage_users" can_manage_users;
237 t#conditional "has_stats" has_stats;
239 (* Pull out the sections in this page. *)
244 let sth = dbh#prepare_cached
245 "select ordering, sectionname, content, divname
246 from contents where pageid = ? order by ordering" in
247 sth#execute [`Int pageid];
250 (function [`Int ordering;
251 (`Null | `String _) as sectionname;
253 (`Null | `String _) as divname] ->
254 let divname, has_divname =
257 | `String divname -> divname, true in
258 let sectionname, has_sectionname =
259 match sectionname with
261 | `String sectionname -> sectionname, true in
262 let linkname = linkname_of_sectionname sectionname in
263 [ "ordering", Template.VarString (string_of_int ordering);
265 Template.VarConditional has_sectionname;
266 "sectionname", Template.VarString sectionname;
267 "linkname", Template.VarString linkname;
270 (Wikilib.xhtml_of_content dbh hostid content);
271 "has_divname", Template.VarConditional has_divname;
272 "divname", Template.VarString divname ]
273 | _ -> assert false) in
275 (* Call an extension to generate the first section in this page? *)
280 let content = extension dbh hostid page' in
282 "ordering", Template.VarString "0";
283 "has_sectionname", Template.VarConditional false;
284 "linkname", Template.VarString "";
285 "content", Template.VarString content;
286 "has_divname", Template.VarConditional true;
287 "divname", Template.VarString "form_div";
289 section :: sections in
291 t#table "sections" sections;
296 t#conditional "user_logged_in" false
297 | User (_, username, _, _) ->
298 t#conditional "user_logged_in" true;
299 t#set "username" username);
301 (* If logged in, we want to update the recently_visited table. *)
302 if pageid <> None then (
304 | User (userid, _, _, _) ->
305 let sth = dbh#prepare_cached "delete from recently_visited
306 where hostid = ? and userid = ?
308 sth#execute [`Int hostid; `Int userid; `String page'];
309 let sth = dbh#prepare_cached
310 "insert into recently_visited (hostid, userid, url)
312 sth#execute [`Int hostid; `Int userid; `String page'];
317 (* Navigation links. *)
319 let max_links = 18 in (* Show no more links than this. *)
321 (* What links here. *)
322 let wlh = what_links_here dbh hostid page' in
323 let wlh = List.take max_links wlh in
324 let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
328 | User (userid, _, _, _) ->
329 (* Recently visited URLs, but don't repeat any from the 'what
330 * links here' section, and don't link to self.
332 let not_urls = page' :: wlh_urls in
333 let limit = max_links - List.length wlh_urls in
334 let qs = Dbi.placeholders (List.length not_urls) in
337 ("select rv.url, p.title, rv.visit_time
338 from recently_visited rv, pages p
339 where rv.hostid = ? and rv.userid = ?
340 and rv.url not in " ^ qs ^ "
341 and rv.hostid = p.hostid and rv.url = p.url
344 let args = List.map (fun s -> `String s) not_urls in
346 ([`Int hostid; `Int userid] @ args @ [`Int limit]);
348 (function [`String url; `String 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 "has_host_css" has_host_css;
405 t#conditional "can_edit" can_edit;
406 t#conditional "can_manage_users" can_manage_users;
407 t#conditional "has_stats" has_stats;
412 (* Fetch a page by name. This function can give three answers:
413 * (1) Page fetched OK (fetches some details of the page).
414 * (2) Page is a redirect (fetches the name of the redirect page).
415 * (3) Page not found in database, could be template or 404 error.
417 (* XXX Should do a case-insensitive matching of URLs, and if the URL differs
418 * in case only should redirect to the lowercase version.
420 let fetch_page page version allow_redirect =
423 if allow_redirect then (
426 "select redirect, id, title, description, last_modified_date,
428 from pages where hostid = ? and url = ?" in
429 sth#execute [`Int hostid; `String page];
431 (match sth#fetch1 () with
432 | [ `Null; `Int id; `String title; `String description;
433 `Timestamp last_modified_date; `Bool has_page_css ] ->
434 FPOK (id, title, description, last_modified_date,
436 | `String redirect :: _ ->
440 Not_found -> FPNotFound)
441 ) else (* redirects not allowed ... *) (
444 "select id, title, description, last_modified_date,
446 from pages where hostid = ? and url = ?" in
447 sth#execute [`Int hostid; `String page];
449 (match sth#fetch1 () with
450 | [ `Int id; `String title; `String description;
451 `Timestamp last_modified_date; `Bool has_page_css ] ->
452 FPOK (id, title, description, last_modified_date,
456 Not_found -> FPNotFound)
461 "select id, title, description, last_modified_date,
464 where hostid = ? and id = ? and
465 (url = ? or url_deleted = ?)" in
466 sth#execute [`Int hostid; `Int version;
467 `String page; `String page];
469 (match sth#fetch1 () with
470 | [ `Int id; `String title; `String description;
471 `Timestamp last_modified_date; `Bool has_page_css ] ->
472 FPOK (id, title, description, last_modified_date,
476 Not_found -> FPNotFound)
479 (* Here we deal with the complex business of redirects and versions. *)
480 (* Only allow the no_redirect and version syntax for editors. *)
481 let allow_redirect, version =
483 not (q#param_true "no_redirect"),
484 try Some (int_of_string (q#param "version")) with Not_found -> None
488 let rec loop page' i =
489 if i > max_redirect then (
490 error ~title:"Too many redirections" ~back_button:true
491 q ("Too many redirects between pages. This may happen because " ^
492 "of a cycle of redirections.");
495 match fetch_page page' version allow_redirect with
496 | FPOK (pageid, title, description, last_modified_date, has_page_css)->
497 (* Check if the page is also a template. *)
498 let extension = get_extension page' in
499 make_page title (Some description) (Some pageid)
500 (printable_date last_modified_date) has_page_css
501 version page page' extension
502 | FPRedirect page' ->
505 (* Might be a templated page with no content in it. *)
506 let extension = get_extension page' in
507 (match extension with
508 | (Some _) as extension ->
510 make_page title None None
511 "Now" false None page page'
519 register_script ~restrict:[CanView] run