Added a search box on every page, controlled by a global setting
[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.23 2004/09/27 16:21:09 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
29 open Cocanwiki
30 open Cocanwiki_template
31 open Cocanwiki_ok
32 open Cocanwiki_date
33 open Cocanwiki_server_settings
34
35 (* Maximum level of redirection. *)
36 let max_redirect = 4
37
38 type fp_status = FPOK of int * string * string * Dbi.datetime * bool
39                | FPRedirect 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 xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
53
54 let run r (q : cgi) (dbh : Dbi.connection) hostid {edit_anon=edit_anon} user =
55   let template_page = get_template dbh hostid "page.html" in
56   let template_404  = get_template dbh hostid "page_404.html" in
57
58   let page = q#param "page" in
59   let page = if page = "" then "index" else page in
60
61   (* Host-specific fields. *)
62   let sth = dbh#prepare_cached "select css is not null,
63                                        feedback_email is not null,
64                                        mailing_list, search_box
65                                   from hosts where id = ?" in
66   sth#execute [`Int hostid];
67   let has_host_css, has_feedback_email, mailing_list, search_box =
68     match sth#fetch1 () with
69       | [ `Bool has_host_css; `Bool has_feedback_email; `Bool mailing_list;
70           `Bool search_box ] ->
71           has_host_css, has_feedback_email, mailing_list, search_box
72       | _ -> assert false in
73
74   (* Can the user edit?  Manage users?  etc. *)
75   let can_edit = can_edit edit_anon user in
76   let can_manage_users = can_manage_users user in
77   let can_manage_contacts = can_manage_contacts user in
78   let can_manage_site = can_manage_site user in
79   let can_edit_global_css = can_edit_global_css user in
80
81   (* Do we have a stats page set up? *)
82   let has_stats = server_settings_stats_page dbh <> None in
83
84   (* Given the referer string, return the list of search terms.  If none
85    * can be found, then throws Not_found.
86    *)
87   let search_terms_from_referer referer =
88     let _, argnames =
89       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
90     let args = Cgi_args.parse referer in
91     let argname =
92       List.find (fun argname -> List.mem_assoc argname args) argnames in
93     let search_string = List.assoc argname args in
94     Pcre.split ~rex:split_words search_string
95   in
96
97   (* Given a full page of XHTML, highlight search terms found in the
98    * <body> part of the page.
99    *)
100   let highlight_search_terms xhtml search_terms span_class =
101     (* Split the original XHTML into strings and tags.  For example if
102      * the original string is: "This is some <b>bold</b> text.<br/>", then
103      * after this step we will have the following list:
104      * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
105      *)
106     let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
107     let xhtml = Array.to_list xhtml in
108     let xhtml = List.map (fun matches -> matches.(0)) xhtml in
109
110     (* Find the <body> ... </body> tags.  We only want to apply
111      * highlighting to tags within this area.
112      *)
113     let rec list_split f acc = function
114       | [] -> List.rev acc, []
115       | ((x :: _) as xs) when f x -> List.rev acc, xs
116       | x :: xs ->
117           let acc = x :: acc in
118           list_split f acc xs
119     in
120     let head, body =
121       list_split (fun str -> String.starts_with str "<body") [] xhtml in
122     let body, tail =
123       list_split ((=) "</body>") [] body in
124     (* NB: Hopefully, xhtml = head @ body @ tail. *)
125
126     (* The search terms are a list of simple words.  Turn into a big
127      * regular expression, because we want to substitute for each.  We
128      * end up with a regexp like '(word1|word2|word3)'.
129      *)
130     let rex =
131       Pcre.regexp ~flags:[`CASELESS]
132         ("(" ^ String.concat "|" search_terms ^ ")") in
133
134     (* Do the substitution, but only on text, not elements! *)
135     let body =
136       let subst text =
137         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
138       in
139       List.map (fun str ->
140                   if String.length str > 0 && str.[0] != '<' then
141                     Pcre.substitute ~rex ~subst str
142                   else
143                     str) body in
144
145     (* Join the XHTML fragments back together again. *)
146     String.concat "" (List.concat [ head ; body ; tail ])
147   in
148
149   (* This code generates ordinary pages. *)
150   let make_page title description pageid last_modified_date has_page_css
151       version page page' =
152     let t = template_page in
153     t#set "title" title;
154     t#set "description" description;
155     t#set "pageid" (string_of_int pageid);
156     t#set "last_modified_date" (printable_date last_modified_date);
157
158     if page <> page' then (* redirection *) (
159       t#set "page" page';
160       t#set "original_page" page; (* XXX title - get it from database *)
161       t#conditional "redirected" true
162     ) else (
163       t#set "page" page;
164       t#conditional "redirected" false
165     );
166
167     t#conditional "has_host_css" has_host_css;
168     t#conditional "has_page_css" has_page_css;
169
170     t#conditional "has_feedback_email" has_feedback_email;
171     t#conditional "mailing_list" mailing_list;
172     t#conditional "search_box" search_box;
173
174     t#conditional "can_edit" can_edit;
175     t#conditional "can_manage_users" can_manage_users;
176     t#conditional "can_manage_contacts" can_manage_contacts;
177     t#conditional "can_manage_site" can_manage_site;
178     t#conditional "can_edit_global_css" can_edit_global_css;
179
180     t#conditional "has_stats" has_stats;
181
182     (* Pull out the sections in this page. *)
183     let sth = dbh#prepare_cached
184                 "select ordering, sectionname, content, divname
185                    from contents
186                   where pageid = ?
187                   order by ordering" in
188     sth#execute [`Int pageid];
189
190     let sections =
191       sth#map
192         (function [`Int ordering;
193                    (`Null | `String _) as sectionname;
194                    `String content;
195                    (`Null | `String _) as divname] ->
196            let divname, has_divname =
197              match divname with
198                  `Null -> "", false
199                | `String divname -> divname, true in
200            let sectionname, has_sectionname =
201              match sectionname with
202                  `Null -> "", false
203                | `String sectionname -> sectionname, true in
204            let linkname = linkname_of_sectionname sectionname in
205            [ "ordering", Template.VarString (string_of_int ordering);
206              "has_sectionname", Template.VarConditional has_sectionname;
207              "sectionname", Template.VarString sectionname;
208              "linkname", Template.VarString linkname;
209              "content",
210                Template.VarString
211                  (Wikilib.xhtml_of_content dbh hostid content);
212              "has_divname", Template.VarConditional has_divname;
213              "divname", Template.VarString divname ]
214            | _ -> assert false) in
215
216     t#table "sections" sections;
217
218     (* Are we showing an old version of the page?  If so, warn. *)
219     (match version with
220          None ->
221            t#conditional "is_old_version" false
222        | Some pageid ->
223            t#conditional "is_old_version" true;
224            t#set "old_version" (string_of_int pageid));
225
226     (* Login status. *)
227     (match user with
228          Anonymous ->
229            t#conditional "user_logged_in" false
230        | User (_, username, _) ->
231            t#conditional "user_logged_in" true;
232            t#set "username" username);
233
234     (* If we are coming from a search engine then we want to highlight
235      * search terms throughout the whole page ...
236      *)
237     try
238       let referer = Table.get (Request.headers_in r) "Referer" in
239       let search_terms = search_terms_from_referer referer in
240
241       (* Highlight the search terms. *)
242       let xhtml = t#to_string in
243       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
244
245       (* Deliver the page. *)
246       q#header ();
247       print_string r xhtml
248     with
249         Not_found ->
250           (* No referer / no search terms / not a search engine referer. *)
251           q#template t
252   in
253
254   (* This code generates 404 pages. *)
255   let make_404 () =
256     Request.set_status r 404;           (* Return a 404 error code. *)
257
258     let t = template_404 in
259     t#set "page" page;
260
261     let search_terms =
262       String.map
263         (function
264              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
265            | _ -> ' ') page in
266
267     t#set "search_terms" search_terms;
268
269     t#conditional "has_host_css" has_host_css;
270
271     t#conditional "can_edit" can_edit;
272     t#conditional "can_manage_users" can_manage_users;
273     t#conditional "can_manage_contacts" can_manage_contacts;
274     t#conditional "can_manage_site" can_manage_site;
275     t#conditional "can_edit_global_css" can_edit_global_css;
276
277     t#conditional "has_stats" has_stats;
278
279     q#template t
280   in
281
282   (* Fetch a page by name.  This function can give three answers:
283    * (1) Page fetched OK (fetches some details of the page).
284    * (2) Page is a redirect (fetches the name of the redirect page).
285    * (3) Page not found in database, ie. 404 error.
286    *)
287   (* XXX Should do a case-insensitive matching of URLs, and if the URL differs
288    * in case only should redirect to the lowercase version.
289    *)
290   let fetch_page page version allow_redirect =
291     match version with
292       | None ->
293           if allow_redirect then (
294             let sth =
295               dbh#prepare_cached
296                 "select redirect, id, title, description, last_modified_date,
297                         css is not null
298                    from pages where hostid = ? and url = ?" in
299             sth#execute [`Int hostid; `String page];
300             (try
301                (match sth#fetch1 () with
302                   | [ `Null; `Int id; `String title; `String description;
303                       `Timestamp last_modified_date; `Bool has_page_css ] ->
304                       FPOK (id, title, description, last_modified_date,
305                             has_page_css)
306                   | `String redirect :: _ ->
307                       FPRedirect redirect
308                   | _ -> assert false)
309              with
310                  Not_found -> FPNotFound)
311           ) else (* redirects not allowed ... *) (
312             let sth =
313               dbh#prepare_cached
314                 "select id, title, description, last_modified_date,
315                         css is not null
316                    from pages where hostid = ? and url = ?" in
317             sth#execute [`Int hostid; `String page];
318             (try
319                (match sth#fetch1 () with
320                   | [ `Int id; `String title; `String description;
321                       `Timestamp last_modified_date; `Bool has_page_css ] ->
322                       FPOK (id, title, description, last_modified_date,
323                             has_page_css)
324                   | _ -> assert false)
325              with
326                  Not_found -> FPNotFound)
327           )
328       | Some version ->
329             let sth =
330               dbh#prepare_cached
331                 "select id, title, description, last_modified_date,
332                         css is not null
333                    from pages
334                   where hostid = ? and id = ? and
335                         (url = ? or url_deleted = ?)" in
336             sth#execute [`Int hostid; `Int version;
337                          `String page; `String page];
338             (try
339                (match sth#fetch1 () with
340                   | [ `Int id; `String title; `String description;
341                       `Timestamp last_modified_date; `Bool has_page_css ] ->
342                       FPOK (id, title, description, last_modified_date,
343                             has_page_css)
344                   | _ -> assert false)
345              with
346                  Not_found -> FPNotFound)
347   in
348
349   (* Here we deal with the complex business of redirects and versions. *)
350   (* Only allow the no_redirect and version syntax for editors. *)
351   let allow_redirect, version =
352     if can_edit then (
353       not (q#param_true "no_redirect"),
354       try Some (int_of_string (q#param "version")) with Not_found -> None
355     ) else
356       (true, None) in
357
358   let rec loop page' i =
359     if i > max_redirect then (
360       error ~title:"Too many redirections" ~back_button:true
361         q ("Too many redirects between pages.  This may happen because " ^
362            "of a cycle of redirections.");
363       return ()
364     ) else
365       match fetch_page page' version allow_redirect with
366         | FPOK (pageid, title, description, last_modified_date, has_page_css)->
367             make_page title description pageid last_modified_date has_page_css
368               version page page'
369         | FPRedirect page' ->
370             loop page' (i+1)
371         | FPNotFound ->
372             make_404 ()
373   in
374   loop page 0
375
376 let () =
377   register_script run