Conservative & probably buggy implementation of breadcrumbs.
[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.55 2006/08/14 17:56:59 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 open Cocanwiki_extensions
37 open Cocanwiki_strings
38
39 type fp_status =
40   | FPOK of int32 * string * string * string option * Calendar.t * bool
41       * bool option
42   | FPInternalRedirect of string
43   | FPExternalRedirect of string
44   | FPNotFound
45
46 (* Referer strings which help us decide if the user came from
47  * a search engine and highlight terms in the page appropriately.
48  *)
49 let search_engines = [
50   Pcre.regexp "^http://.*google\\.", [ "q"; "as_q"; "as_epq"; "as_oq" ];
51   Pcre.regexp "^http://.*yahoo\\.", [ "p" ];
52   Pcre.regexp "^http://.*msn\\.", [ "q"; "MT" ]
53 ]
54 let split_words = Pcre.regexp "\\W+"
55
56 let split_qs_re = Pcre.regexp "\\?"
57
58 let xhtml_re = Pcre.regexp "<.*?>|[^<>]+"
59
60 let run r (q : cgi) dbh hostid
61     ({ edit_anon = edit_anon; view_anon = view_anon } as host)
62     user =
63   let page = q#param "page" in
64   let page = if page = "" then "index" else page in
65
66   (* The main "page" template is split in two to improve the speed of
67    * delivery of the page.  The very first part ("page_header.html")
68    * contains the page <head>, crucially including all the links to the
69    * stylesheets.  We send this first and flush it out to the client so
70    * that the client can begin requesting stylesheets, background images
71    * and so on.  After this we compose the main page ("page.html") and
72    * send it out second.
73    *)
74
75   let template_page_header =
76     get_template ~page dbh hostid "page_header.html" in
77   let template_page = get_template ~page dbh hostid "page.html" in
78
79   (* This is the simpler template for 404 pages. *)
80   let template_404_header  = get_template dbh hostid "page_404_header.html" in
81   let template_404  = get_template dbh hostid "page_404.html" in
82
83   (* Host-specific fields. *)
84   let rows =
85     PGSQL(dbh)
86       "select feedback_email is not null, mailing_list, navigation
87          from hosts where id = $hostid" in
88   let has_feedback_email, mailing_list, navigation =
89     match rows with
90       | [Some has_feedback_email, mailing_list, navigation] ->
91           has_feedback_email, mailing_list, navigation
92       | _ -> assert false in
93
94   (* User permissions. *)
95   let can_edit = can_edit host user in
96   let can_manage_users = can_manage_users host user in
97
98   (* Do we have a stats page set up? *)
99   let has_stats = server_settings_stats_page dbh <> None in
100
101   (* Given the referer string, return the list of search terms.  If none
102    * can be found, then throws Not_found.
103    *)
104   let search_terms_from_referer referer =
105     let _, argnames =
106       List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
107     let url, qs =
108       match Pcre.split ~rex:split_qs_re ~max:2 referer with
109         | [url] | [url;""] -> url, ""
110         | [url;qs] -> url, qs
111         | _ -> assert false in
112     let args = Cgi_args.parse qs in
113     let argname =
114       List.find (fun argname -> List.mem_assoc argname args) argnames in
115     let search_string = List.assoc argname args in
116     Pcre.split ~rex:split_words search_string
117   in
118
119   (* Given a full page of XHTML, highlight search terms found in the
120    * <body> part of the page.
121    *)
122   let highlight_search_terms xhtml search_terms span_class =
123     (* Split the original XHTML into strings and tags.  For example if
124      * the original string is: "This is some <b>bold</b> text.<br/>", then
125      * after this step we will have the following list:
126      * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
127      *)
128     let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
129     let xhtml = Array.to_list xhtml in
130     let xhtml = List.map (fun matches -> matches.(0)) xhtml in
131
132     (* Find the <body> ... </body> tags.  We only want to apply
133      * highlighting to tags within this area.
134      *)
135     let rec list_split f acc = function
136       | [] -> List.rev acc, []
137       | ((x :: _) as xs) when f x -> List.rev acc, xs
138       | x :: xs ->
139           let acc = x :: acc in
140           list_split f acc xs
141     in
142     let head, body =
143       list_split (fun str -> String.starts_with str "<body") [] xhtml in
144     let body, tail =
145       list_split ((=) "</body>") [] body in
146     (* NB: Hopefully, xhtml = head @ body @ tail. *)
147
148     (* The search terms are a list of simple words.  Turn into a big
149      * regular expression, because we want to substitute for each.  We
150      * end up with a regexp like '(word1|word2|word3)'.
151      *)
152     let rex =
153       Pcre.regexp ~flags:[`CASELESS]
154         ("(" ^ String.concat "|" search_terms ^ ")") in
155
156     (* Do the substitution, but only on text, not elements! *)
157     let body =
158       let subst text =
159         "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
160       in
161       List.map (fun str ->
162                   if String.length str > 0 && str.[0] != '<' then
163                     Pcre.substitute ~rex ~subst str
164                   else
165                     str) body in
166
167     (* Join the XHTML fragments back together again. *)
168     String.concat "" (List.concat [ head ; body ; tail ])
169   in
170
171   (* Check the templates table for extensions. *)
172   let get_extension url =
173     try
174       let name =
175         List.hd (
176           PGSQL(dbh) "select extension from templates
177                        where $url ~ url_regexp
178                        order by ordering
179                        limit 1"
180         ) in
181       Some (List.assoc name !extensions)
182     with
183       Not_found | ExtList.List.Empty_list | Failure "hd" -> None
184   in
185
186   (* This code generates ordinary pages. *)
187   let make_page title description keywords
188       pageid last_modified_date has_page_css noodp
189       version page page' extension =
190     let t = template_page in
191     let th = template_page_header in
192     (*t#set "title" title; - nothing uses ::title:: on page.html - removed *)
193
194     (* Page title, h1 and superdirs (if any). *)
195     th#set "title" title;
196
197     let superdirs, h1 =
198       match String.nsplit title "/" with
199       | [] -> [], ""
200       | [h1] -> [], h1
201       | xs ->
202           let xs = List.rev xs in
203           let h1 = List.hd xs in
204           let superdirs = List.rev (List.tl xs) in
205
206           (* Check the superdirs are reasonable, then convert them
207            * into paths or redlinks.
208            * If any of this fails, then there are no superdirs.
209            *)
210           try
211             let pathsofar = ref "" in
212             let superdirs =
213               List.mapi (
214                 fun i name ->
215                   (* Path will be something like "Dir1/Dir2".  We want
216                    * a URL like "dir1/dir2".
217                    *)
218                   let path =
219                     if i = 0 then name else !pathsofar ^ "/" ^ name in
220                   (* Path so far reasonable? *)
221                   let url, redlink =
222                     match Wikilib.generate_url_of_title r dbh hostid path with
223                     | Wikilib.GenURL_Duplicate url -> url, None
224                     | Wikilib.GenURL_OK url -> url, Some path
225                     | Wikilib.GenURL_BadURL | Wikilib.GenURL_TooShort ->
226                         raise Exit in
227                   pathsofar := path;
228                   name, url, redlink
229               ) superdirs in
230             superdirs, h1
231           with
232             Exit -> [], title in
233
234     let superdirs = List.map (
235       fun (name, url, redlink) ->
236         let is_redlink, redlink_title =
237           match redlink with
238           | None -> false, ""
239           | Some title -> true, title in
240         [ "url", Template.VarString url;
241           "name", Template.VarString name;
242           "is_redlink", Template.VarConditional is_redlink;
243           "redlink_title", Template.VarString redlink_title ]
244     ) superdirs in
245
246     th#conditional "has_superdirs" (superdirs <> []);
247     th#table "superdirs" superdirs;
248     th#set "h1" h1;
249
250     t#set "last_modified_date" last_modified_date;
251
252     (match description with
253          None -> th#conditional "has_description" false
254        | Some description ->
255            th#conditional "has_description" true;
256            th#set "description" description);
257
258     (match keywords with
259          None -> th#conditional "has_keywords" false
260        | Some keywords ->
261            th#conditional "has_keywords" true;
262            th#set "keywords" keywords);
263
264     if page <> page' then (* redirection *) (
265       t#set "page" page';
266       th#set "page" page';
267       t#set "original_page" page; (* XXX title - get it from database *)
268       t#conditional "redirected" true
269     ) else (
270       t#set "page" page;
271       th#set "page" page;
272       t#conditional "redirected" false
273     );
274
275     th#conditional "has_page_css" has_page_css;
276
277     (* If the per-page noodp is not null, set the noodp flag here.  Otherwise
278      * we will use the default (from hosts.global_noodp) which was set
279      * in Cocanwiki_template.
280      *)
281     (match noodp with
282      | None -> ()
283      | Some b -> th#conditional "noodp" b);
284
285     (* Are we showing an old version of the page?  If so, warn. *)
286     (match version with
287          None ->
288            t#conditional "is_old_version" false;
289            th#conditional "is_old_version" false
290        | Some pageid ->
291            t#conditional "is_old_version" true;
292            th#conditional "is_old_version" true;
293            t#set "old_version" (Int32.to_string pageid);
294            th#set "old_version" (Int32.to_string pageid));
295
296     (* Just before we show the header, call any registered pre-page
297      * handlers.  They might want to send cookies.
298      *)
299     List.iter (fun handler ->
300                  handler r q dbh hostid page') !pre_page_handlers;
301
302     (* At this point, we can print out the header and flush it back to
303      * the user, allowing the browser to start fetching stylesheets
304      * and background images while we compose the page.
305      *)
306     q#header ();
307     ignore (print_string r th#to_string);
308     ignore (Request.rflush r);
309
310     t#conditional "has_feedback_email" has_feedback_email;
311     t#conditional "mailing_list" mailing_list;
312     t#conditional "navigation" navigation;
313
314     t#conditional "can_edit" can_edit;
315     t#conditional "can_manage_users" can_manage_users;
316     t#conditional "has_stats" has_stats;
317
318     (* Pull out the sections in this page. *)
319     let sections =
320       match pageid with
321           None -> []
322         | Some pageid ->
323             let rows = PGSQL(dbh)
324               "select ordering, sectionname, content, divname, jsgo
325                  from contents where pageid = $pageid order by ordering" in
326
327             List.map
328               (fun (ordering, sectionname, content, divname, jsgo) ->
329                  let divname, has_divname =
330                    match divname with
331                    | None -> "", false
332                    | Some divname -> divname, true in
333                  let jsgo, has_jsgo =
334                    match jsgo with
335                    | None -> "", false
336                    | Some jsgo -> jsgo, true in
337                  let sectionname, has_sectionname =
338                    match sectionname with
339                    | None -> "", false
340                    | Some sectionname -> sectionname, true in
341                  let linkname = linkname_of_sectionname sectionname in
342                  [ "ordering", Template.VarString (Int32.to_string ordering);
343                    "has_sectionname",
344                      Template.VarConditional has_sectionname;
345                    "sectionname", Template.VarString sectionname;
346                    "linkname", Template.VarString linkname;
347                    "content",
348                      Template.VarString
349                        (Wikilib.xhtml_of_content r dbh hostid content);
350                    "has_divname", Template.VarConditional has_divname;
351                    "divname", Template.VarString divname;
352                    "has_jsgo", Template.VarConditional has_jsgo;
353                    "jsgo", Template.VarString jsgo ]) rows in
354
355     (* Call an extension to generate the first section in this page? *)
356     let sections =
357       match extension with
358           None -> sections
359         | Some extension ->
360             let content = extension r dbh hostid page' in
361             let section = [
362               "ordering", Template.VarString "0";
363               "has_sectionname", Template.VarConditional false;
364               "linkname", Template.VarString "";
365               "content", Template.VarString content;
366               "has_divname", Template.VarConditional true;
367               "divname", Template.VarString "form_div";
368               "has_jsgo", Template.VarConditional false;
369               "jsgo", Template.VarString "";
370             ] in
371             section :: sections in
372
373     t#table "sections" sections;
374
375     (* Login status. *)
376     (match user with
377          Anonymous ->
378            t#conditional "user_logged_in" false
379        | User (_, username, _, _) ->
380            t#conditional "user_logged_in" true;
381            t#set "username" username);
382
383     (* Can anonymous users create accounts?  If not them we don't
384      * want to offer to create accounts for them.
385      *)
386     t#conditional "create_account_anon" host.create_account_anon;
387
388     (* If logged in, we want to update the recently_visited table. *)
389     if pageid <> None then (
390       match user with
391         | User (userid, _, _, _) ->
392             (try
393                PGSQL(dbh)
394                  "delete from recently_visited
395                    where hostid = $hostid and userid = $userid
396                      and url = $page'";
397                PGSQL(dbh)
398                  "insert into recently_visited (hostid, userid, url)
399                   values ($hostid, $userid, $page')";
400                PGOCaml.commit dbh;
401              with
402                exn ->
403                  (* Exceptions here are non-fatal.  Just print them. *)
404                  prerr_endline "exception updating recently_visited:";
405                  prerr_endline (Printexc.to_string exn);
406                  PGOCaml.rollback dbh;
407             );
408             PGOCaml.begin_work dbh;
409         | _ -> ()
410     );
411
412     (* Navigation links. *)
413     if navigation then (
414       let max_links = 18 in             (* Show no more links than this. *)
415
416       (* What links here. *)
417       let wlh = what_links_here dbh hostid page' in
418       let wlh = List.take max_links wlh in
419       let wlh_urls = List.map fst wlh in (* Just the URLs ... *)
420
421       let rv =
422         match user with
423           | User (userid, _, _, _) ->
424               (* Recently visited URLs, but don't repeat any from the 'what
425                * links here' section, and don't link to self.
426                *)
427               let not_urls = page' :: wlh_urls in
428               let limit = Int32.of_int (max_links - List.length wlh_urls) in
429               let rows =
430                 PGSQL(dbh)
431                   "select rv.url, p.title, rv.visit_time
432                      from recently_visited rv, pages p
433                     where rv.hostid = $hostid and rv.userid = $userid
434                       and rv.url not in $@not_urls
435                       and rv.hostid = p.hostid and rv.url = p.url
436                     order by 3 desc
437                     limit $limit" in
438               List.map (
439                 fun (url, title, _) -> url, title
440               ) rows
441           | _ -> [] in
442
443       (* Links to page. *)
444       let f (page, title) = [ "page", Template.VarString page;
445                               "title", Template.VarString title ] in
446       let table = List.map f wlh in
447       t#table "what_links_here" table;
448       t#conditional "has_what_links_here" (wlh <> []);
449
450       let table = List.map f rv in
451       t#table "recently_visited" table;
452       t#conditional "has_recently_visited" (rv <> []);
453
454       (* If both lists are empty (ie. an empty navigation box would
455        * appear), then disable navigation altogether.
456        *)
457       if wlh = [] && rv = [] then t#conditional "navigation" false
458     );
459
460     (* If we are coming from a search engine then we want to highlight
461      * search terms throughout the whole page ...
462      *)
463     try
464       let referer = Table.get (Request.headers_in r) "Referer" in
465       let search_terms = search_terms_from_referer referer in
466
467       (* Highlight the search terms. *)
468       let xhtml = t#to_string in
469       let xhtml = highlight_search_terms xhtml search_terms "search_term" in
470
471       (* Deliver the page. *)
472       ignore (print_string r xhtml)
473     with
474         Not_found ->
475           (* No referer / no search terms / not a search engine referer. *)
476           ignore (print_string r t#to_string)
477   in
478
479   (* This code generates 404 pages. *)
480   let make_404 () =
481     Request.set_status r 404;           (* Return a 404 error code. *)
482
483     let th = template_404_header in
484     th#set "page" page;
485
486     let search_terms =
487       String.map
488         (function
489              ('a'..'z' | 'A'..'Z' | '0'..'9') as c -> c
490            | _ -> ' ') page in
491
492     th#set "search_terms" search_terms;
493
494     (* Flush out the header while we start the search. *)
495     q#header ();
496     ignore (print_string r th#to_string);
497     ignore (Request.rflush r);
498
499     let t = template_404 in
500     t#set "query" search_terms;
501     t#set "canonical_hostname" host.canonical_hostname;
502
503     (* This is a simplified version of the code in search.ml. *)
504     let have_results =
505       (* Get the keywords from the query string. *)
506       let keywords = Pcre.split ~rex:split_words search_terms in
507       let keywords =
508         List.filter (fun s -> not (string_is_whitespace s)) keywords in
509       let keywords = List.map String.lowercase keywords in
510
511       (* Turn the keywords into a tsearch2 ts_query string. *)
512       let tsquery = String.concat "&" keywords in
513
514       (* Search the titles first. *)
515       let rows =
516         PGSQL(dbh)
517             "select url, title, last_modified_date,
518                     (lower (title) = lower ($search_terms)) as exact
519                from pages
520               where hostid = $hostid
521                 and url is not null
522                 and redirect is null
523                 and title_description_fti @@ to_tsquery ('default', $tsquery)
524               order by exact desc, last_modified_date desc, title" in
525
526       let titles =
527         List.map (function
528                   | (Some url, title, last_modified, _) ->
529                       url, title, last_modified
530                   | _ -> assert false) rows in
531
532       let have_titles = titles <> [] in
533       t#conditional "have_titles" have_titles;
534
535       (* Search the contents. *)
536       let rows =
537         PGSQL(dbh)
538           "select c.id, p.url, p.title, p.last_modified_date
539              from contents c, pages p
540             where c.pageid = p.id
541               and p.hostid = $hostid
542               and url is not null
543               and p.redirect is null
544               and c.content_fti @@ to_tsquery ('default', $tsquery)
545             order by p.last_modified_date desc, p.title
546             limit 50" in
547
548       let contents =
549         List.map (function
550                   | (contentid, Some url, title, last_modified) ->
551                       contentid, url, title, last_modified
552                   | _ -> assert false) rows in
553
554       let have_contents = contents <> [] in
555       t#conditional "have_contents" have_contents;
556
557       (* Pull out the actual text which matched so we can generate a summary.
558        * XXX tsearch2 can actually do better than this by emboldening
559        * the text which maps.
560        *)
561       let content_map =
562         if contents = [] then []
563         else (
564           let rows =
565             let contentids =
566               List.map (fun (contentid, _,_,_) -> contentid) contents in
567             PGSQL(dbh)
568               "select id, sectionname, content from contents
569                 where id in $@contentids" in
570           List.map (fun (id, sectionname, content) ->
571                       id, (sectionname, content)) rows
572         ) in
573
574       (* Generate the final tables. *)
575       let table =
576         List.map (fun (url, title, last_modified) ->
577                     let last_modified = printable_date last_modified in
578                     [ "url", Template.VarString url;
579                       "title", Template.VarString title;
580                       "last_modified", Template.VarString last_modified ]
581                  ) titles in
582       t#table "titles" table;
583
584       let table =
585         List.map
586           (fun (contentid, url, title, last_modified) ->
587              let sectionname, content = List.assoc contentid content_map in
588              let have_sectionname, sectionname =
589                match sectionname with
590                  None -> false, ""
591                | Some sectionname -> true, sectionname in
592              let content =
593                truncate 160
594                  (Wikilib.text_of_xhtml
595                     (Wikilib.xhtml_of_content r dbh hostid content)) in
596              let linkname = linkname_of_sectionname sectionname in
597              let last_modified = printable_date last_modified in
598              [ "url", Template.VarString url;
599                "title", Template.VarString title;
600                "have_sectionname", Template.VarConditional have_sectionname;
601                "sectionname", Template.VarString sectionname;
602                "linkname", Template.VarString linkname;
603                "content", Template.VarString content;
604                "last_modified", Template.VarString last_modified ]
605           ) contents in
606       t#table "contents" table;
607
608       (* Do we have any results? *)
609       let have_results = have_titles || have_contents in
610       have_results in
611     t#conditional "have_results" have_results;
612
613     (* Deliver the rest of the page. *)
614     ignore (print_string r t#to_string)
615   in
616
617   (* Fetch a page by name.  This function can give three answers:
618    * (1) Page fetched OK (fetches some details of the page).
619    * (2) Page is a redirect (fetches the name of the redirect page).
620    * (3) Page not found in database, could be template or 404 error.
621    *)
622   let fetch_page page version allow_redirect =
623     match version with
624       | None ->
625           if allow_redirect then (
626             let rows = PGSQL(dbh)
627               "select url, redirect, id, title, description, keywords,
628                       last_modified_date, css is not null, noodp
629                  from pages
630                 where hostid = $hostid and lower (url) = lower ($page)" in
631             match rows with
632             | [Some page', _, _, _, _, _, _, _, _]
633                 when page <> page' -> (* different case *)
634                 FPExternalRedirect page'
635             | [ _, None, id, title, description, keywords,
636                 last_modified_date, has_page_css, noodp ] ->
637                 let has_page_css = Option.get has_page_css in
638                 FPOK (id, title, description, keywords, last_modified_date,
639                       has_page_css, noodp)
640             | [_, Some redirect, _, _, _, _, _, _, _] ->
641                 FPInternalRedirect redirect
642             | [] -> FPNotFound
643             | _ -> assert false
644           ) else (* redirects not allowed ... *) (
645             let rows = PGSQL(dbh)
646               "select id, title, description, keywords, last_modified_date,
647                       css is not null, noodp
648                  from pages where hostid = $hostid and url = $page" in
649             match rows with
650             | [ id, title, description, keywords,
651                 last_modified_date, has_page_css, noodp ] ->
652                 let has_page_css = Option.get has_page_css in
653                 FPOK (id, title, description, keywords, last_modified_date,
654                       has_page_css, noodp)
655             | [] -> FPNotFound
656             | _ -> assert false
657           )
658       | Some version ->
659           let rows = PGSQL(dbh)
660             "select id, title, description, keywords, last_modified_date,
661                     css is not null, noodp
662                from pages
663               where hostid = $hostid and id = $version and
664                     (url = $page or url_deleted = $page)" in
665           match rows with
666           | [ id, title, description, keywords,
667               last_modified_date, has_page_css, noodp ] ->
668               let has_page_css = Option.get has_page_css in
669               FPOK (id, title, description, keywords, last_modified_date,
670                     has_page_css, noodp)
671           | [] -> FPNotFound
672           | _ -> assert false
673   in
674
675   (* Here we deal with the complex business of redirects and versions. *)
676   (* Only allow the no_redirect and version syntax for editors. *)
677   let allow_redirect, version =
678     if can_edit then (
679       not (q#param_true "no_redirect"),
680       try Some (Int32.of_string (q#param "version")) with Not_found -> None
681     ) else
682       (true, None) in
683
684   let rec loop page' i =
685     if i > max_redirect then (
686       error ~title:"Too many redirections" ~back_button:true
687         dbh hostid q
688         ("Too many redirects between pages.  This may happen because " ^
689          "of a cycle of redirections.");
690       return ()
691     ) else
692       match fetch_page page' version allow_redirect with
693         | FPOK (pageid, title, description, keywords,
694                 last_modified_date, has_page_css, noodp)->
695             (* Check if the page is also a template. *)
696             let extension = get_extension page' in
697             make_page title (Some description) keywords (Some pageid)
698               (printable_date last_modified_date) has_page_css noodp
699               version page page' extension
700         | FPInternalRedirect page' ->
701             loop page' (i+1)
702         | FPExternalRedirect page' ->
703             (* This normally happens when a user has requested an uppercase
704              * page name.  We redirect to the true (lowercase) version.
705              *)
706             q#redirect ("http://" ^ host.hostname ^ "/" ^ page')
707         | FPNotFound ->
708             (* Might be a templated page with no content in it. *)
709             let extension = get_extension page' in
710             (match extension with
711                | (Some _) as extension ->
712                    let title = page' in
713                    make_page title None None None
714                      "Now" false None None page page'
715                      extension
716                | None ->
717                    make_404 ())
718   in
719   loop page 0
720
721 let () =
722   register_script ~restrict:[CanView] run