If anonymous account creation isn't allowed, then don't print
[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.47 2006/07/26 13:19:49 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
37 type fp_status = FPOK of int32 * string * string * Calendar.t * bool
38                | FPInternalRedirect of string
39                | FPExternalRedirect of string
40                | FPNotFound
41
42 (* Referer strings which help us decide if the user came from
43  * a search engine and highlight terms in the page appropriately.
44  *)
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" ]
49 ]
50 let split_words = Pcre.regexp "\\W+"
51
52 let split_qs_re = Pcre.regexp "\\?"
53
54 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
55
56 let run r (q : cgi) dbh hostid
57     ({ edit_anon = edit_anon; view_anon = view_anon } as host)
58     user =
59   let page = q#param "page" in
60   let page = if page = "" then "index" else page in
61
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
68    * send it out second.
69    *)
70
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
74
75   (* This is the simpler template for 404 pages. *)
76   let template_404  = get_template dbh hostid "page_404.html" in
77
78   (* Host-specific fields. *)
79   let rows = PGSQL(dbh)
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 =
83     match rows with
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
88
89   (* User permissions. *)
90   let can_edit = can_edit host user in
91   let can_manage_users = can_manage_users host user in
92
93   (* Do we have a stats page set up? *)
94   let has_stats = server_settings_stats_page dbh <> None in
95
96   (* Given the referer string, return the list of search terms.  If none
97    * can be found, then throws Not_found.
98    *)
99   let search_terms_from_referer referer =
100     let _, argnames =
101       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
102     let url, qs =
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
108     let argname =
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
112   in
113
114   (* Given a full page of XHTML, highlight search terms found in the
115    * <body> part of the page.
116    *)
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/>" ]
122      *)
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
126
127     (* Find the <body> ... </body> tags.  We only want to apply
128      * highlighting to tags within this area.
129      *)
130     let rec list_split f acc = function
131       | [] -> List.rev acc, []
132       | ((x :: _) as xs) when f x -> List.rev acc, xs
133       | x :: xs ->
134           let acc = x :: acc in
135           list_split f acc xs
136     in
137     let head, body =
138       list_split (fun str -> String.starts_with str "<body") [] xhtml in
139     let body, tail =
140       list_split ((=) "</body>") [] body in
141     (* NB: Hopefully, xhtml = head @ body @ tail. *)
142
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)'.
146      *)
147     let rex =
148       Pcre.regexp ~flags:[`CASELESS]
149         ("(" ^ String.concat "|" search_terms ^ ")") in
150
151     (* Do the substitution, but only on text, not elements! *)
152     let body =
153       let subst text =
154         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
155       in
156       List.map (fun str ->
157                   if String.length str > 0 && str.[0] != '<' then
158                     Pcre.substitute ~rex ~subst str
159                   else
160                     str) body in
161
162     (* Join the XHTML fragments back together again. *)
163     String.concat "" (List.concat [ head ; body ; tail ])
164   in
165
166   (* Check the templates table for extensions. *)
167   let get_extension url =
168     try
169       let name =
170         List.hd (
171           PGSQL(dbh) "select extension from templates
172                        where $url ~ url_regexp
173                        order by ordering
174                        limit 1"
175         ) in
176       Some (List.assoc name !extensions)
177     with
178       Not_found | ExtList.List.Empty_list -> None
179   in
180
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
186     t#set "title" title;
187     th#set "title" title;
188     t#set "last_modified_date" last_modified_date;
189
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);
195
196     if page <> page' then (* redirection *) (
197       t#set "page" page';
198       th#set "page" page';
199       t#set "original_page" page; (* XXX title - get it from database *)
200       t#conditional "redirected" true
201     ) else (
202       t#set "page" page;
203       th#set "page" page;
204       t#conditional "redirected" false
205     );
206
207     th#conditional "has_host_css" has_host_css;
208     th#conditional "has_page_css" has_page_css;
209
210     (* Are we showing an old version of the page?  If so, warn. *)
211     (match version with
212          None ->
213            t#conditional "is_old_version" false;
214            th#conditional "is_old_version" false
215        | Some pageid ->
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));
220
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.
224      *)
225     q#header ();
226     ignore (print_string r th#to_string);
227     ignore (Request.rflush r);
228
229     t#conditional "has_feedback_email" has_feedback_email;
230     t#conditional "mailing_list" mailing_list;
231     t#conditional "navigation" navigation;
232
233     t#conditional "can_edit" can_edit;
234     t#conditional "can_manage_users" can_manage_users;
235     t#conditional "has_stats" has_stats;
236
237     (* Pull out the sections in this page. *)
238     let sections =
239       match pageid with
240           None -> []
241         | Some pageid ->
242             let rows = PGSQL(dbh)
243               "select ordering, sectionname, content, divname, jsgo
244                  from contents where pageid = $pageid order by ordering" in
245
246             List.map
247               (fun (ordering, sectionname, content, divname, jsgo) ->
248                  let divname, has_divname =
249                    match divname with
250                    | None -> "", false
251                    | Some divname -> divname, true in
252                  let jsgo, has_jsgo =
253                    match jsgo with
254                    | None -> "", false
255                    | Some jsgo -> jsgo, true in
256                  let sectionname, has_sectionname =
257                    match sectionname with
258                    | None -> "", false
259                    | Some sectionname -> sectionname, true in
260                  let linkname = linkname_of_sectionname sectionname in
261                  [ "ordering", Template.VarString (Int32.to_string ordering);
262                    "has_sectionname",
263                      Template.VarConditional has_sectionname;
264                    "sectionname", Template.VarString sectionname;
265                    "linkname", Template.VarString linkname;
266                    "content",
267                      Template.VarString
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
273
274     (* Call an extension to generate the first section in this page? *)
275     let sections =
276       match extension with
277           None -> sections
278         | Some extension ->
279             let content = extension dbh hostid page' in
280             let section = [
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 "";
289             ] in
290             section :: sections in
291
292     t#table "sections" sections;
293
294     (* Login status. *)
295     (match user with
296          Anonymous ->
297            t#conditional "user_logged_in" false
298        | User (_, username, _, _) ->
299            t#conditional "user_logged_in" true;
300            t#set "username" username);
301
302     (* Can anonymous users create accounts?  If not them we don't
303      * want to offer to create accounts for them.
304      *)
305     t#conditional "create_account_anon" host.create_account_anon;
306
307     (* If logged in, we want to update the recently_visited table. *)
308     if pageid <> None then (
309       match user with
310         | User (userid, _, _, _) ->
311             PGSQL(dbh)
312               "delete from recently_visited
313                 where hostid = $hostid and userid = $userid and url = $page'";
314             PGSQL(dbh)
315               "insert into recently_visited (hostid, userid, url)
316                values ($hostid, $userid, $page')";
317             PGOCaml.commit dbh;
318             PGOCaml.begin_work dbh;
319         | _ -> ()
320     );
321
322     (* Navigation links. *)
323     if navigation then (
324       let max_links = 18 in             (* Show no more links than this. *)
325
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 ... *)
330
331       let rv =
332         match user with
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.
336                *)
337               let not_urls = page' :: wlh_urls in
338               let limit = Int32.of_int (max_links - List.length wlh_urls) in
339               let rows =
340                 PGSQL(dbh)
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
346                     order by 3 desc
347                     limit $limit" in
348               List.map (
349                 fun (url, title, _) -> url, title
350               ) rows
351           | _ -> [] in
352
353       (* Links to page. *)
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 <> []);
359
360       let table = List.map f rv in
361       t#table "recently_visited" table;
362       t#conditional "has_recently_visited" (rv <> []);
363
364       (* If both lists are empty (ie. an empty navigation box would
365        * appear), then disable navigation altogether.
366        *)
367       if wlh = [] && rv = [] then t#conditional "navigation" false
368     );
369
370     (* If we are coming from a search engine then we want to highlight
371      * search terms throughout the whole page ...
372      *)
373     try
374       let referer = Table.get (Request.headers_in r) "Referer" in
375       let search_terms = search_terms_from_referer referer in
376
377       (* Highlight the search terms. *)
378       let xhtml = t#to_string in
379       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
380
381       (* Deliver the page. *)
382       ignore (print_string r xhtml)
383     with
384         Not_found ->
385           (* No referer / no search terms / not a search engine referer. *)
386           ignore (print_string r t#to_string)
387   in
388
389   (* This code generates 404 pages. *)
390   let make_404 () =
391     Request.set_status r 404;           (* Return a 404 error code. *)
392
393     let t = template_404 in
394     t#set "page" page;
395
396     let search_terms =
397       String.map
398         (function
399              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
400            | _ -> ' ') page in
401
402     t#set "search_terms" search_terms;
403
404     t#conditional "can_edit" can_edit;
405     t#conditional "can_manage_users" can_manage_users;
406     t#conditional "has_stats" has_stats;
407
408     q#template t
409   in
410
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.
415    *)
416   let fetch_page page version allow_redirect =
417     match version with
418       | None ->
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
423                  from pages
424                 where hostid = $hostid and lower (url) = lower ($page)" in
425             match rows with
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,
433                       has_page_css)
434             | [_, Some redirect, _, _, _, _, _] ->
435                 FPInternalRedirect redirect
436             | [] -> FPNotFound
437             | _ -> assert false
438           ) else (* redirects not allowed ... *) (
439             let rows = PGSQL(dbh)
440               "select id, title, description, last_modified_date,
441                       css is not null
442                  from pages where hostid = $hostid and url = $page" in
443             match rows with
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,
448                       has_page_css)
449             | [] -> FPNotFound
450             | _ -> assert false
451           )
452       | Some version ->
453           let rows = PGSQL(dbh)
454             "select id, title, description, last_modified_date,
455                     css is not null
456                from pages
457               where hostid = $hostid and id = $version and
458                     (url = $page or url_deleted = $page)" in
459           match rows with
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,
464                     has_page_css)
465           | [] -> FPNotFound
466           | _ -> assert false
467   in
468
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 =
472     if can_edit then (
473       not (q#param_true "no_redirect"),
474       try Some (Int32.of_string (q#param "version")) with Not_found -> None
475     ) else
476       (true, None) in
477
478   let rec loop page' i =
479     if i > max_redirect then (
480       error ~title:"Too many redirections" ~back_button:true
481         dbh hostid q
482         ("Too many redirects between pages.  This may happen because " ^
483          "of a cycle of redirections.");
484       return ()
485     ) else
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' ->
494             loop page' (i+1)
495         | FPExternalRedirect page' ->
496             (* This normally happens when a user has requested an uppercase
497              * page name.  We redirect to the true (lowercase) version.
498              *)
499             q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
500         | FPNotFound ->
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 ->
505                    let title = page' in
506                    make_page title None None
507                      "Now" false None page page'
508                      extension
509                | None ->
510                    make_404 ())
511   in
512   loop page 0
513
514 let () =
515   register_script ~restrict:[CanView] run