Added external functions allowing the markup to be extended.
[cocanwiki.git] / scripts / page.ml
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.48 2006/07/27 16:46:55 rich Exp $
5  *
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.
10  *
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.
15  *
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.
20  *)
21
22 open Apache
23 open Registry
24 open Cgi
25 open Printf
26
27 open ExtString
28 open ExtList
29
30 open Cocanwiki
31 open Cocanwiki_template
32 open Cocanwiki_ok
33 open Cocanwiki_date
34 open Cocanwiki_server_settings
35 open Cocanwiki_links
36 open Cocanwiki_extensions
37
38 type fp_status = FPOK of int32 * string * string * Calendar.t * bool
39                | FPInternalRedirect of string
40                | FPExternalRedirect of string
41                | FPNotFound
42
43 (* Referer strings which help us decide if the user came from
44  * a search engine and highlight terms in the page appropriately.
45  *)
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" ]
50 ]
51 let split_words = Pcre.regexp "\\W+"
52
53 let split_qs_re = Pcre.regexp "\\?"
54
55 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
56
57 let run r (q : cgi) dbh hostid
58     ({ edit_anon = edit_anon; view_anon = view_anon } as host)
59     user =
60   let page = q#param "page" in
61   let page = if page = "" then "index" else page in
62
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
69    * send it out second.
70    *)
71
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
75
76   (* This is the simpler template for 404 pages. *)
77   let template_404  = get_template dbh hostid "page_404.html" in
78
79   (* Host-specific fields. *)
80   let rows = PGSQL(dbh)
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 =
84     match rows with
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
89
90   (* User permissions. *)
91   let can_edit = can_edit host user in
92   let can_manage_users = can_manage_users host user in
93
94   (* Do we have a stats page set up? *)
95   let has_stats = server_settings_stats_page dbh <> None in
96
97   (* Given the referer string, return the list of search terms.  If none
98    * can be found, then throws Not_found.
99    *)
100   let search_terms_from_referer referer =
101     let _, argnames =
102       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
103     let url, qs =
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
109     let argname =
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
113   in
114
115   (* Given a full page of XHTML, highlight search terms found in the
116    * <body> part of the page.
117    *)
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/>" ]
123      *)
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
127
128     (* Find the <body> ... </body> tags.  We only want to apply
129      * highlighting to tags within this area.
130      *)
131     let rec list_split f acc = function
132       | [] -> List.rev acc, []
133       | ((x :: _) as xs) when f x -> List.rev acc, xs
134       | x :: xs ->
135           let acc = x :: acc in
136           list_split f acc xs
137     in
138     let head, body =
139       list_split (fun str -> String.starts_with str "<body") [] xhtml in
140     let body, tail =
141       list_split ((=) "</body>") [] body in
142     (* NB: Hopefully, xhtml = head @ body @ tail. *)
143
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)'.
147      *)
148     let rex =
149       Pcre.regexp ~flags:[`CASELESS]
150         ("(" ^ String.concat "|" search_terms ^ ")") in
151
152     (* Do the substitution, but only on text, not elements! *)
153     let body =
154       let subst text =
155         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
156       in
157       List.map (fun str ->
158                   if String.length str > 0 && str.[0] != '<' then
159                     Pcre.substitute ~rex ~subst str
160                   else
161                     str) body in
162
163     (* Join the XHTML fragments back together again. *)
164     String.concat "" (List.concat [ head ; body ; tail ])
165   in
166
167   (* Check the templates table for extensions. *)
168   let get_extension url =
169     try
170       let name =
171         List.hd (
172           PGSQL(dbh) "select extension from templates
173                        where $url ~ url_regexp
174                        order by ordering
175                        limit 1"
176         ) in
177       Some (List.assoc name !extensions)
178     with
179       Not_found | ExtList.List.Empty_list -> None
180   in
181
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
187     t#set "title" title;
188     th#set "title" title;
189     t#set "last_modified_date" last_modified_date;
190
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);
196
197     if page <> page' then (* redirection *) (
198       t#set "page" page';
199       th#set "page" page';
200       t#set "original_page" page; (* XXX title - get it from database *)
201       t#conditional "redirected" true
202     ) else (
203       t#set "page" page;
204       th#set "page" page;
205       t#conditional "redirected" false
206     );
207
208     th#conditional "has_host_css" has_host_css;
209     th#conditional "has_page_css" has_page_css;
210
211     (* Are we showing an old version of the page?  If so, warn. *)
212     (match version with
213          None ->
214            t#conditional "is_old_version" false;
215            th#conditional "is_old_version" false
216        | Some pageid ->
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));
221
222     (* Just before we show the header, call any registered pre-page
223      * handlers.  They might want to send cookies.
224      *)
225     List.iter (fun handler ->
226                  handler r q dbh hostid page') !pre_page_handlers;
227
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.
231      *)
232     q#header ();
233     ignore (print_string r th#to_string);
234     ignore (Request.rflush r);
235
236     t#conditional "has_feedback_email" has_feedback_email;
237     t#conditional "mailing_list" mailing_list;
238     t#conditional "navigation" navigation;
239
240     t#conditional "can_edit" can_edit;
241     t#conditional "can_manage_users" can_manage_users;
242     t#conditional "has_stats" has_stats;
243
244     (* Pull out the sections in this page. *)
245     let sections =
246       match pageid with
247           None -> []
248         | Some pageid ->
249             let rows = PGSQL(dbh)
250               "select ordering, sectionname, content, divname, jsgo
251                  from contents where pageid = $pageid order by ordering" in
252
253             List.map
254               (fun (ordering, sectionname, content, divname, jsgo) ->
255                  let divname, has_divname =
256                    match divname with
257                    | None -> "", false
258                    | Some divname -> divname, true in
259                  let jsgo, has_jsgo =
260                    match jsgo with
261                    | None -> "", false
262                    | Some jsgo -> jsgo, true in
263                  let sectionname, has_sectionname =
264                    match sectionname with
265                    | None -> "", false
266                    | Some sectionname -> sectionname, true in
267                  let linkname = linkname_of_sectionname sectionname in
268                  [ "ordering", Template.VarString (Int32.to_string ordering);
269                    "has_sectionname",
270                      Template.VarConditional has_sectionname;
271                    "sectionname", Template.VarString sectionname;
272                    "linkname", Template.VarString linkname;
273                    "content",
274                      Template.VarString
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
280
281     (* Call an extension to generate the first section in this page? *)
282     let sections =
283       match extension with
284           None -> sections
285         | Some extension ->
286             let content = extension r dbh hostid page' in
287             let section = [
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 "";
296             ] in
297             section :: sections in
298
299     t#table "sections" sections;
300
301     (* Login status. *)
302     (match user with
303          Anonymous ->
304            t#conditional "user_logged_in" false
305        | User (_, username, _, _) ->
306            t#conditional "user_logged_in" true;
307            t#set "username" username);
308
309     (* Can anonymous users create accounts?  If not them we don't
310      * want to offer to create accounts for them.
311      *)
312     t#conditional "create_account_anon" host.create_account_anon;
313
314     (* If logged in, we want to update the recently_visited table. *)
315     if pageid <> None then (
316       match user with
317         | User (userid, _, _, _) ->
318             PGSQL(dbh)
319               "delete from recently_visited
320                 where hostid = $hostid and userid = $userid and url = $page'";
321             PGSQL(dbh)
322               "insert into recently_visited (hostid, userid, url)
323                values ($hostid, $userid, $page')";
324             PGOCaml.commit dbh;
325             PGOCaml.begin_work dbh;
326         | _ -> ()
327     );
328
329     (* Navigation links. *)
330     if navigation then (
331       let max_links = 18 in             (* Show no more links than this. *)
332
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 ... *)
337
338       let rv =
339         match user with
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.
343                *)
344               let not_urls = page' :: wlh_urls in
345               let limit = Int32.of_int (max_links - List.length wlh_urls) in
346               let rows =
347                 PGSQL(dbh)
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
353                     order by 3 desc
354                     limit $limit" in
355               List.map (
356                 fun (url, title, _) -> url, title
357               ) rows
358           | _ -> [] in
359
360       (* Links to page. *)
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 <> []);
366
367       let table = List.map f rv in
368       t#table "recently_visited" table;
369       t#conditional "has_recently_visited" (rv <> []);
370
371       (* If both lists are empty (ie. an empty navigation box would
372        * appear), then disable navigation altogether.
373        *)
374       if wlh = [] && rv = [] then t#conditional "navigation" false
375     );
376
377     (* If we are coming from a search engine then we want to highlight
378      * search terms throughout the whole page ...
379      *)
380     try
381       let referer = Table.get (Request.headers_in r) "Referer" in
382       let search_terms = search_terms_from_referer referer in
383
384       (* Highlight the search terms. *)
385       let xhtml = t#to_string in
386       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
387
388       (* Deliver the page. *)
389       ignore (print_string r xhtml)
390     with
391         Not_found ->
392           (* No referer / no search terms / not a search engine referer. *)
393           ignore (print_string r t#to_string)
394   in
395
396   (* This code generates 404 pages. *)
397   let make_404 () =
398     Request.set_status r 404;           (* Return a 404 error code. *)
399
400     let t = template_404 in
401     t#set "page" page;
402
403     let search_terms =
404       String.map
405         (function
406              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
407            | _ -> ' ') page in
408
409     t#set "search_terms" search_terms;
410
411     t#conditional "can_edit" can_edit;
412     t#conditional "can_manage_users" can_manage_users;
413     t#conditional "has_stats" has_stats;
414
415     q#template t
416   in
417
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.
422    *)
423   let fetch_page page version allow_redirect =
424     match version with
425       | None ->
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
430                  from pages
431                 where hostid = $hostid and lower (url) = lower ($page)" in
432             match rows with
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,
440                       has_page_css)
441             | [_, Some redirect, _, _, _, _, _] ->
442                 FPInternalRedirect redirect
443             | [] -> FPNotFound
444             | _ -> assert false
445           ) else (* redirects not allowed ... *) (
446             let rows = PGSQL(dbh)
447               "select id, title, description, last_modified_date,
448                       css is not null
449                  from pages where hostid = $hostid and url = $page" in
450             match rows with
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,
455                       has_page_css)
456             | [] -> FPNotFound
457             | _ -> assert false
458           )
459       | Some version ->
460           let rows = PGSQL(dbh)
461             "select id, title, description, last_modified_date,
462                     css is not null
463                from pages
464               where hostid = $hostid and id = $version and
465                     (url = $page or url_deleted = $page)" in
466           match rows with
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,
471                     has_page_css)
472           | [] -> FPNotFound
473           | _ -> assert false
474   in
475
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 =
479     if can_edit then (
480       not (q#param_true "no_redirect"),
481       try Some (Int32.of_string (q#param "version")) with Not_found -> None
482     ) else
483       (true, None) in
484
485   let rec loop page' i =
486     if i > max_redirect then (
487       error ~title:"Too many redirections" ~back_button:true
488         dbh hostid q
489         ("Too many redirects between pages.  This may happen because " ^
490          "of a cycle of redirections.");
491       return ()
492     ) else
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' ->
501             loop page' (i+1)
502         | FPExternalRedirect page' ->
503             (* This normally happens when a user has requested an uppercase
504              * page name.  We redirect to the true (lowercase) version.
505              *)
506             q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
507         | FPNotFound ->
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 ->
512                    let title = page' in
513                    make_page title None None
514                      "Now" false None page page'
515                      extension
516                | None ->
517                    make_404 ())
518   in
519   loop page 0
520
521 let () =
522   register_script ~restrict:[CanView] run