+ (* Do we have a stats page set up? *)
+ let has_stats = server_settings_stats_page dbh <> None in
+
+ (* Given the referer string, return the list of search terms. If none
+ * can be found, then throws Not_found.
+ *)
+ let search_terms_from_referer referer =
+ let _, argnames =
+ List.find (fun (rex, _) -> Pcre.pmatch ~rex referer) search_engines in
+ let _, _, args = Cocanwiki_cgi_args.parse referer in
+ let argname =
+ List.find (fun argname -> List.mem_assoc argname args) argnames in
+ let search_string = List.assoc argname args in
+ Pcre.split ~rex:split_words search_string
+ in
+
+ (* Given a full page of XHTML, highlight search terms found in the
+ * <body> part of the page.
+ *)
+ let highlight_search_terms xhtml search_terms span_class =
+ (* Split the original XHTML into strings and tags. For example if
+ * the original string is: "This is some <b>bold</b> text.<br/>", then
+ * after this step we will have the following list:
+ * [ "This is some "; "<b>"; "bold"; "</b>"; " text."; "<br/>" ]
+ *)
+ let xhtml = Pcre.extract_all ~rex:xhtml_re xhtml in
+ let xhtml = Array.to_list xhtml in
+ let xhtml = List.map (fun matches -> matches.(0)) xhtml in
+
+ (* Find the <body> ... </body> tags. We only want to apply
+ * highlighting to tags within this area.
+ *)
+ let rec list_split f acc = function
+ | [] -> List.rev acc, []
+ | ((x :: _) as xs) when f x -> List.rev acc, xs
+ | x :: xs ->
+ let acc = x :: acc in
+ list_split f acc xs
+ in
+ let head, body =
+ list_split (fun str -> String.starts_with str "<body") [] xhtml in
+ let body, tail =
+ list_split ((=) "</body>") [] body in
+ (* NB: Hopefully, xhtml = head @ body @ tail. *)
+
+ (* The search terms are a list of simple words. Turn into a big
+ * regular expression, because we want to substitute for each. We
+ * end up with a regexp like '(word1|word2|word3)'.
+ *)
+ let rex =
+ Pcre.regexp ~flags:[`CASELESS]
+ ("(" ^ String.concat "|" search_terms ^ ")") in
+
+ (* Do the substitution, but only on text, not elements! *)
+ let body =
+ let subst text =
+ "<span class=\"" ^ span_class ^ "\">" ^ text ^ "</span>"
+ in
+ List.map (fun str ->
+ if String.length str > 0 && str.[0] != '<' then
+ Pcre.substitute ~rex ~subst str
+ else
+ str) body in
+
+ (* Join the XHTML fragments back together again. *)
+ String.concat "" (List.concat [ head ; body ; tail ])
+ in
+