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