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