Fixes a couple of personal bugbears:
[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.33 2004/10/17 19:43:19 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 int * string * string * Dbi.datetime * bool
38                | FPRedirect of string
39                | FPNotFound
40
41 (* Referer strings which help us decide if the user came from
42  * a search engine and highlight terms in the page appropriately.
43  *)
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" ]
48 ]
49 let split_words = Pcre.regexp "\\W+"
50
51 let split_qs_re = Pcre.regexp "\\?"
52
53 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
54
55 let run r (q : cgi) (dbh : Dbi.connection) hostid
56     ({ edit_anon = edit_anon;
57        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   let template_page = get_template ~page dbh hostid "page.html" in
63   let template_404  = get_template dbh hostid "page_404.html" in
64
65   (* Host-specific fields. *)
66   let sth = dbh#prepare_cached "select css is not null,
67                                        feedback_email is not null,
68                                        mailing_list, search_box, navigation
69                                   from hosts where id = ?" in
70   sth#execute [`Int hostid];
71   let has_host_css, has_feedback_email, mailing_list, search_box, navigation =
72     match sth#fetch1 () with
73       | [ `Bool has_host_css; `Bool has_feedback_email; `Bool mailing_list;
74           `Bool search_box; `Bool navigation ] ->
75           has_host_css, has_feedback_email, mailing_list, search_box,
76           navigation
77       | _ -> assert false in
78
79   (* Can the user edit?  Manage users?  etc. *)
80   let can_edit = can_edit host user in
81   let can_manage_users = can_manage_users host user in
82   let can_manage_contacts = can_manage_contacts host user in
83   let can_manage_site = can_manage_site host user in
84   let can_edit_global_css = can_edit_global_css host user in
85
86   (* Do we have a stats page set up? *)
87   let has_stats = server_settings_stats_page dbh <> None in
88
89   (* Given the referer string, return the list of search terms.  If none
90    * can be found, then throws Not_found.
91    *)
92   let search_terms_from_referer referer =
93     let _, argnames =
94       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
95     let url, qs =
96       match Pcre.split ~rex:split_qs_re ~max:2 referer with
97         | [url] | [url;""] -> url, ""
98         | [url;qs] -> url, qs
99         | _ -> assert false in
100     let args = Cgi_args.parse qs in
101     let argname =
102       List.find (fun argname -> List.mem_assoc argname args) argnames in
103     let search_string = List.assoc argname args in
104     Pcre.split ~rex:split_words search_string
105   in
106
107   (* Given a full page of XHTML, highlight search terms found in the
108    * <body> part of the page.
109    *)
110   let highlight_search_terms xhtml search_terms span_class =
111     (* Split the original XHTML into strings and tags.  For example if
112      * the original string is: "This is some <b>bold</b> text.<br/>", then
113      * after this step we will have the following list:
114      * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
115      *)
116     let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
117     let xhtml = Array.to_list xhtml in
118     let xhtml = List.map (fun matches -> matches.(0)) xhtml in
119
120     (* Find the <body> ... </body> tags.  We only want to apply
121      * highlighting to tags within this area.
122      *)
123     let rec list_split f acc = function
124       | [] -> List.rev acc, []
125       | ((x :: _) as xs) when f x -> List.rev acc, xs
126       | x :: xs ->
127           let acc = x :: acc in
128           list_split f acc xs
129     in
130     let head, body =
131       list_split (fun str -> String.starts_with str "<body") [] xhtml in
132     let body, tail =
133       list_split ((=) "</body>") [] body in
134     (* NB: Hopefully, xhtml = head @ body @ tail. *)
135
136     (* The search terms are a list of simple words.  Turn into a big
137      * regular expression, because we want to substitute for each.  We
138      * end up with a regexp like '(word1|word2|word3)'.
139      *)
140     let rex =
141       Pcre.regexp ~flags:[`CASELESS]
142         ("(" ^ String.concat "|" search_terms ^ ")") in
143
144     (* Do the substitution, but only on text, not elements! *)
145     let body =
146       let subst text =
147         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
148       in
149       List.map (fun str ->
150                   if String.length str > 0 && str.[0] != '<' then
151                     Pcre.substitute ~rex ~subst str
152                   else
153                     str) body in
154
155     (* Join the XHTML fragments back together again. *)
156     String.concat "" (List.concat [ head ; body ; tail ])
157   in
158
159   (* Check the templates table for extensions. *)
160   let get_extension url =
161     let sth = dbh#prepare_cached "select extension from templates
162                                    where ? ~ url_regexp
163                                    order by ordering
164                                    limit 1" in
165     sth#execute [`String url];
166
167     try
168       let name = sth#fetch1string () in
169       Some (List.assoc name !extensions)
170     with
171         Not_found -> None
172   in
173
174   (* This code generates ordinary pages. *)
175   let make_page title description pageid last_modified_date has_page_css
176       version page page' extension =
177     let t = template_page in
178     t#set "title" title;
179     t#set "last_modified_date" last_modified_date;
180
181     (match description with
182          None -> t#conditional "has_description" false
183        | Some description ->
184            t#conditional "has_description" true;
185            t#set "description" description);
186
187     if page <> page' then (* redirection *) (
188       t#set "page" page';
189       t#set "original_page" page; (* XXX title - get it from database *)
190       t#conditional "redirected" true
191     ) else (
192       t#set "page" page;
193       t#conditional "redirected" false
194     );
195
196     t#conditional "has_host_css" has_host_css;
197     t#conditional "has_page_css" has_page_css;
198
199     t#conditional "has_feedback_email" has_feedback_email;
200     t#conditional "mailing_list" mailing_list;
201     t#conditional "search_box" search_box;
202     t#conditional "navigation" navigation;
203
204     t#conditional "can_edit" can_edit;
205     t#conditional "can_manage_users" can_manage_users;
206     t#conditional "can_manage_contacts" can_manage_contacts;
207     t#conditional "can_manage_site" can_manage_site;
208     t#conditional "can_edit_global_css" can_edit_global_css;
209
210     t#conditional "has_stats" has_stats;
211
212     (* Pull out the sections in this page. *)
213     let sections =
214       match pageid with
215           None -> []
216         | Some pageid ->
217             let sth = dbh#prepare_cached
218                         "select ordering, sectionname, content, divname
219                            from contents where pageid = ? order by ordering" in
220             sth#execute [`Int pageid];
221
222             sth#map
223               (function [`Int ordering;
224                          (`Null | `String _) as sectionname;
225                          `String content;
226                          (`Null | `String _) as divname] ->
227                  let divname, has_divname =
228                    match divname with
229                        `Null -> "", false
230                      | `String divname -> divname, true in
231                  let sectionname, has_sectionname =
232                    match sectionname with
233                        `Null -> "", false
234                      | `String sectionname -> sectionname, true in
235                  let linkname = linkname_of_sectionname sectionname in
236                  [ "ordering", Template.VarString (string_of_int ordering);
237                    "has_sectionname",
238                      Template.VarConditional has_sectionname;
239                    "sectionname", Template.VarString sectionname;
240                    "linkname", Template.VarString linkname;
241                    "content",
242                      Template.VarString
243                        (Wikilib.xhtml_of_content dbh hostid content);
244                    "has_divname", Template.VarConditional has_divname;
245                    "divname", Template.VarString divname ]
246                  | _ -> assert false) in
247
248     (* Call an extension to generate the first section in this page? *)
249     let sections =
250       match extension with
251           None -> sections
252         | Some extension ->
253             let content = extension dbh hostid page' in
254             let section = [
255               "ordering", Template.VarString "0";
256               "has_sectionname", Template.VarConditional false;
257               "linkname", Template.VarString "";
258               "content", Template.VarString content;
259               "has_divname", Template.VarConditional true;
260               "divname", Template.VarString "form_div";
261             ] in
262             section :: sections in
263
264     t#table "sections" sections;
265
266     (* Are we showing an old version of the page?  If so, warn. *)
267     (match version with
268          None ->
269            t#conditional "is_old_version" false
270        | Some pageid ->
271            t#conditional "is_old_version" true;
272            t#set "old_version" (string_of_int pageid));
273
274     (* Login status. *)
275     (match user with
276          Anonymous ->
277            t#conditional "user_logged_in" false
278        | User (_, username, _) ->
279            t#conditional "user_logged_in" true;
280            t#set "username" username);
281
282     (* If logged in, we want to update the recently_visited table. *)
283     if pageid <> None then (
284       match user with
285         | User (userid, _, _) ->
286             let sth = dbh#prepare_cached "delete from recently_visited
287                                            where hostid = ? and userid = ?
288                                              and url = ?" in
289             sth#execute [`Int hostid; `Int userid; `String page'];
290             let sth = dbh#prepare_cached
291                         "insert into recently_visited (hostid, userid, url)
292                          values (?, ?, ?)" in
293             sth#execute [`Int hostid; `Int userid; `String page'];
294             dbh#commit ()
295         | _ -> ()
296     );
297
298     (* Navigation links. *)
299     if navigation then (
300       let max_links = 18 in             (* Show no more links than this. *)
301
302       (* What links here. *)
303       let wlh = what_links_here dbh hostid page' in
304       let wlh = List.take max_links wlh in
305       let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
306
307       let rv =
308         match user with
309           | User (userid, _, _) ->
310               (* Recently visited URLs, but don't repeat any from the 'what
311                * links here' section, and don't link to self.
312                *)
313               let not_urls = page' :: wlh_urls in
314               let limit = max_links - List.length wlh_urls in
315               let qs = Dbi.placeholders (List.length not_urls) in
316               let sth =
317                 dbh#prepare_cached
318                   ("select rv.url, p.title, rv.visit_time
319                       from recently_visited rv, pages p
320                      where rv.hostid = ? and rv.userid = ?
321                        and rv.url not in " ^ qs ^ "
322                        and rv.hostid = p.hostid and rv.url = p.url
323                      order by 3 desc
324                      limit ?") in
325               let args = List.map (fun s -> `String s) not_urls in
326               sth#execute
327                 ([`Int hostid; `Int userid] @ args @ [`Int limit]);
328               sth#map
329                 (function [`String url; `String title; _] ->
330                    url, title
331                    | _ -> assert false)
332           | _ -> [] in
333
334       (* Links to page. *)
335       let f (page, title) = [ "page", Template.VarString page;
336                               "title", Template.VarString title ] in
337       let table = List.map f wlh in
338       t#table "what_links_here" table;
339       t#conditional "has_what_links_here" (wlh <> []);
340
341       let table = List.map f rv in
342       t#table "recently_visited" table;
343       t#conditional "has_recently_visited" (rv <> []);
344
345       (* If both lists are empty (ie. an empty navigation box would
346        * appear), then disable navigation altogether.
347        *)
348       if wlh = [] && rv = [] then t#conditional "navigation" false
349     );
350
351     (* If we are coming from a search engine then we want to highlight
352      * search terms throughout the whole page ...
353      *)
354     try
355       let referer = Table.get (Request.headers_in r) "Referer" in
356       let search_terms = search_terms_from_referer referer in
357
358       (* Highlight the search terms. *)
359       let xhtml = t#to_string in
360       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
361
362       (* Deliver the page. *)
363       q#header ();
364       print_string r xhtml
365     with
366         Not_found ->
367           (* No referer / no search terms / not a search engine referer. *)
368           q#template t
369   in
370
371   (* This code generates 404 pages. *)
372   let make_404 () =
373     Request.set_status r 404;           (* Return a 404 error code. *)
374
375     let t = template_404 in
376     t#set "page" page;
377
378     let search_terms =
379       String.map
380         (function
381              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
382            | _ -> ' ') page in
383
384     t#set "search_terms" search_terms;
385
386     t#conditional "has_host_css" has_host_css;
387
388     t#conditional "can_edit" can_edit;
389     t#conditional "can_manage_users" can_manage_users;
390     t#conditional "can_manage_contacts" can_manage_contacts;
391     t#conditional "can_manage_site" can_manage_site;
392     t#conditional "can_edit_global_css" can_edit_global_css;
393
394     t#conditional "has_stats" has_stats;
395
396     q#template t
397   in
398
399   (* Fetch a page by name.  This function can give three answers:
400    * (1) Page fetched OK (fetches some details of the page).
401    * (2) Page is a redirect (fetches the name of the redirect page).
402    * (3) Page not found in database, could be template or 404 error.
403    *)
404   (* XXX Should do a case-insensitive matching of URLs, and if the URL differs
405    * in case only should redirect to the lowercase version.
406    *)
407   let fetch_page page version allow_redirect =
408     match version with
409       | None ->
410           if allow_redirect then (
411             let sth =
412               dbh#prepare_cached
413                 "select redirect, id, title, description, last_modified_date,
414                         css is not null
415                    from pages where hostid = ? and url = ?" in
416             sth#execute [`Int hostid; `String page];
417             (try
418                (match sth#fetch1 () with
419                   | [ `Null; `Int id; `String title; `String description;
420                       `Timestamp last_modified_date; `Bool has_page_css ] ->
421                       FPOK (id, title, description, last_modified_date,
422                             has_page_css)
423                   | `String redirect :: _ ->
424                       FPRedirect redirect
425                   | _ -> assert false)
426              with
427                  Not_found -> FPNotFound)
428           ) else (* redirects not allowed ... *) (
429             let sth =
430               dbh#prepare_cached
431                 "select id, title, description, last_modified_date,
432                         css is not null
433                    from pages where hostid = ? and url = ?" in
434             sth#execute [`Int hostid; `String page];
435             (try
436                (match sth#fetch1 () with
437                   | [ `Int id; `String title; `String description;
438                       `Timestamp last_modified_date; `Bool has_page_css ] ->
439                       FPOK (id, title, description, last_modified_date,
440                             has_page_css)
441                   | _ -> assert false)
442              with
443                  Not_found -> FPNotFound)
444           )
445       | Some version ->
446             let sth =
447               dbh#prepare_cached
448                 "select id, title, description, last_modified_date,
449                         css is not null
450                    from pages
451                   where hostid = ? and id = ? and
452                         (url = ? or url_deleted = ?)" in
453             sth#execute [`Int hostid; `Int version;
454                          `String page; `String page];
455             (try
456                (match sth#fetch1 () with
457                   | [ `Int id; `String title; `String description;
458                       `Timestamp last_modified_date; `Bool has_page_css ] ->
459                       FPOK (id, title, description, last_modified_date,
460                             has_page_css)
461                   | _ -> assert false)
462              with
463                  Not_found -> FPNotFound)
464   in
465
466   (* Here we deal with the complex business of redirects and versions. *)
467   (* Only allow the no_redirect and version syntax for editors. *)
468   let allow_redirect, version =
469     if can_edit then (
470       not (q#param_true "no_redirect"),
471       try Some (int_of_string (q#param "version")) with Not_found -> None
472     ) else
473       (true, None) in
474
475   let rec loop page' i =
476     if i > max_redirect then (
477       error ~title:"Too many redirections" ~back_button:true
478         q ("Too many redirects between pages.  This may happen because " ^
479            "of a cycle of redirections.");
480       return ()
481     ) else
482       match fetch_page page' version allow_redirect with
483         | FPOK (pageid, title, description, last_modified_date, has_page_css)->
484             (* Check if the page is also a template. *)
485             let extension = get_extension page' in
486             make_page title (Some description) (Some pageid)
487               (printable_date last_modified_date) has_page_css
488               version page page' extension
489         | FPRedirect page' ->
490             loop page' (i+1)
491         | FPNotFound ->
492             (* Might be a templated page with no content in it. *)
493             let extension = get_extension page' in
494             (match extension with
495                | (Some _) as extension ->
496                    let title = page' in
497                    make_page title None None
498                      "Now" false None page page'
499                      extension
500                | None ->
501                    make_404 ())
502   in
503   loop page 0
504
505 let () =
506   register_script ~restrict:[CanView] run