Added 'broken links' script.
[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.26 2004/10/07 16:54:24 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 split_qs_re = Pcre.regexp "\\?"
53
54 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
55
56 let run r (q : cgi) (dbh : Dbi.connection) hostid
57     ({ edit_anon = edit_anon;
58        view_anon = view_anon } as host)
59     user =
60   let template_page = get_template dbh hostid "page.html" in
61   let template_404  = get_template dbh hostid "page_404.html" in
62
63   let page = q#param "page" in
64   let page = if page = "" then "index" else page in
65
66   (* Host-specific fields. *)
67   let sth = dbh#prepare_cached "select css is not null,
68                                        feedback_email is not null,
69                                        mailing_list, search_box
70                                   from hosts where id = ?" in
71   sth#execute [`Int hostid];
72   let has_host_css, has_feedback_email, mailing_list, search_box =
73     match sth#fetch1 () with
74       | [ `Bool has_host_css; `Bool has_feedback_email; `Bool mailing_list;
75           `Bool search_box ] ->
76           has_host_css, has_feedback_email, mailing_list, search_box
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
203     t#conditional "can_edit" can_edit;
204     t#conditional "can_manage_users" can_manage_users;
205     t#conditional "can_manage_contacts" can_manage_contacts;
206     t#conditional "can_manage_site" can_manage_site;
207     t#conditional "can_edit_global_css" can_edit_global_css;
208
209     t#conditional "has_stats" has_stats;
210
211     (* Pull out the sections in this page. *)
212     let sections =
213       match pageid with
214           None -> []
215         | Some pageid ->
216             let sth = dbh#prepare_cached
217                         "select ordering, sectionname, content, divname
218                            from contents where pageid = ? order by ordering" in
219             sth#execute [`Int pageid];
220
221             sth#map
222               (function [`Int ordering;
223                          (`Null | `String _) as sectionname;
224                          `String content;
225                          (`Null | `String _) as divname] ->
226                  let divname, has_divname =
227                    match divname with
228                        `Null -> "", false
229                      | `String divname -> divname, true in
230                  let sectionname, has_sectionname =
231                    match sectionname with
232                        `Null -> "", false
233                      | `String sectionname -> sectionname, true in
234                  let linkname = linkname_of_sectionname sectionname in
235                  [ "ordering", Template.VarString (string_of_int ordering);
236                    "has_sectionname",
237                      Template.VarConditional has_sectionname;
238                    "sectionname", Template.VarString sectionname;
239                    "linkname", Template.VarString linkname;
240                    "content",
241                      Template.VarString
242                        (Wikilib.xhtml_of_content dbh hostid content);
243                    "has_divname", Template.VarConditional has_divname;
244                    "divname", Template.VarString divname ]
245                  | _ -> assert false) in
246
247     (* Call an extension to generate the first section in this page? *)
248     let sections =
249       match extension with
250           None -> sections
251         | Some extension ->
252             let content = extension dbh hostid page' in
253             let section = [
254               "ordering", Template.VarString "0";
255               "has_sectionname", Template.VarConditional false;
256               "linkname", Template.VarString "";
257               "content", Template.VarString content;
258               "has_divname", Template.VarConditional true;
259               "divname", Template.VarString "form_div";
260             ] in
261             section :: sections in
262
263     t#table "sections" sections;
264
265     (* Are we showing an old version of the page?  If so, warn. *)
266     (match version with
267          None ->
268            t#conditional "is_old_version" false
269        | Some pageid ->
270            t#conditional "is_old_version" true;
271            t#set "old_version" (string_of_int pageid));
272
273     (* Login status. *)
274     (match user with
275          Anonymous ->
276            t#conditional "user_logged_in" false
277        | User (_, username, _) ->
278            t#conditional "user_logged_in" true;
279            t#set "username" username);
280
281     (* If we are coming from a search engine then we want to highlight
282      * search terms throughout the whole page ...
283      *)
284     try
285       let referer = Table.get (Request.headers_in r) "Referer" in
286       let search_terms = search_terms_from_referer referer in
287
288       (* Highlight the search terms. *)
289       let xhtml = t#to_string in
290       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
291
292       (* Deliver the page. *)
293       q#header ();
294       print_string r xhtml
295     with
296         Not_found ->
297           (* No referer / no search terms / not a search engine referer. *)
298           q#template t
299   in
300
301   (* This code generates 404 pages. *)
302   let make_404 () =
303     Request.set_status r 404;           (* Return a 404 error code. *)
304
305     let t = template_404 in
306     t#set "page" page;
307
308     let search_terms =
309       String.map
310         (function
311              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
312            | _ -> ' ') page in
313
314     t#set "search_terms" search_terms;
315
316     t#conditional "has_host_css" has_host_css;
317
318     t#conditional "can_edit" can_edit;
319     t#conditional "can_manage_users" can_manage_users;
320     t#conditional "can_manage_contacts" can_manage_contacts;
321     t#conditional "can_manage_site" can_manage_site;
322     t#conditional "can_edit_global_css" can_edit_global_css;
323
324     t#conditional "has_stats" has_stats;
325
326     q#template t
327   in
328
329   (* Fetch a page by name.  This function can give three answers:
330    * (1) Page fetched OK (fetches some details of the page).
331    * (2) Page is a redirect (fetches the name of the redirect page).
332    * (3) Page not found in database, could be template or 404 error.
333    *)
334   (* XXX Should do a case-insensitive matching of URLs, and if the URL differs
335    * in case only should redirect to the lowercase version.
336    *)
337   let fetch_page page version allow_redirect =
338     match version with
339       | None ->
340           if allow_redirect then (
341             let sth =
342               dbh#prepare_cached
343                 "select redirect, id, title, description, last_modified_date,
344                         css is not null
345                    from pages where hostid = ? and url = ?" in
346             sth#execute [`Int hostid; `String page];
347             (try
348                (match sth#fetch1 () with
349                   | [ `Null; `Int id; `String title; `String description;
350                       `Timestamp last_modified_date; `Bool has_page_css ] ->
351                       FPOK (id, title, description, last_modified_date,
352                             has_page_css)
353                   | `String redirect :: _ ->
354                       FPRedirect redirect
355                   | _ -> assert false)
356              with
357                  Not_found -> FPNotFound)
358           ) else (* redirects not allowed ... *) (
359             let sth =
360               dbh#prepare_cached
361                 "select id, title, description, last_modified_date,
362                         css is not null
363                    from pages where hostid = ? and url = ?" in
364             sth#execute [`Int hostid; `String page];
365             (try
366                (match sth#fetch1 () with
367                   | [ `Int id; `String title; `String description;
368                       `Timestamp last_modified_date; `Bool has_page_css ] ->
369                       FPOK (id, title, description, last_modified_date,
370                             has_page_css)
371                   | _ -> assert false)
372              with
373                  Not_found -> FPNotFound)
374           )
375       | Some version ->
376             let sth =
377               dbh#prepare_cached
378                 "select id, title, description, last_modified_date,
379                         css is not null
380                    from pages
381                   where hostid = ? and id = ? and
382                         (url = ? or url_deleted = ?)" in
383             sth#execute [`Int hostid; `Int version;
384                          `String page; `String page];
385             (try
386                (match sth#fetch1 () with
387                   | [ `Int id; `String title; `String description;
388                       `Timestamp last_modified_date; `Bool has_page_css ] ->
389                       FPOK (id, title, description, last_modified_date,
390                             has_page_css)
391                   | _ -> assert false)
392              with
393                  Not_found -> FPNotFound)
394   in
395
396   (* Here we deal with the complex business of redirects and versions. *)
397   (* Only allow the no_redirect and version syntax for editors. *)
398   let allow_redirect, version =
399     if can_edit then (
400       not (q#param_true "no_redirect"),
401       try Some (int_of_string (q#param "version")) with Not_found -> None
402     ) else
403       (true, None) in
404
405   let rec loop page' i =
406     if i > max_redirect then (
407       error ~title:"Too many redirections" ~back_button:true
408         q ("Too many redirects between pages.  This may happen because " ^
409            "of a cycle of redirections.");
410       return ()
411     ) else
412       match fetch_page page' version allow_redirect with
413         | FPOK (pageid, title, description, last_modified_date, has_page_css)->
414             (* Check if the page is also a template. *)
415             let extension = get_extension page' in
416             make_page title (Some description) (Some pageid)
417               (printable_date last_modified_date) has_page_css
418               version page page' extension
419         | FPRedirect page' ->
420             loop page' (i+1)
421         | FPNotFound ->
422             (* Might be a templated page with no content in it. *)
423             let extension = get_extension page' in
424             (match extension with
425                | (Some _) as extension ->
426                    let title = page' in
427                    make_page title None None
428                      "Now" false None page page'
429                      extension
430                | None ->
431                    make_404 ())
432   in
433   loop page 0
434
435 let () =
436   register_script ~restrict:[CanView] run