2 (* Copyright (C) 2002, HELM Team.
4 * This file is part of HELM, an Hypertextual, Electronic
5 * Library of Mathematics, developed at the Computer Science
6 * Department, University of Bologna, Italy.
8 * HELM is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * HELM is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with HELM; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23 * For details, see the HELM World-Wide-Web page,
24 * http://cs.unibo.it/helm/.
28 let debug_print s = if debug then prerr_endline s;;
29 Http_common.debug := true;;
33 let daemon_name = "Search Engine";;
34 let default_port = 58085;;
35 let port_env_var = "SEARCH_ENGINE_PORT";;
37 let pages_dir = "html";; (* relative to searchEngine's document root *)
38 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
39 let interactive_interpretation_choice_TPL = pages_dir ^ "/templateambigpdq2.html";;
40 let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";;
42 exception Chat_unfinished
44 (** chain application of Pcre substitutions *)
45 let rec apply_substs substs line =
48 | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
49 (** fold like function on files *)
50 let fold_file f init fname =
51 let inchan = open_in fname in
52 let rec fold_lines' value =
54 let line = input_line inchan in
55 fold_lines' (f value line)
56 with End_of_file -> value
58 let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
61 (** iter like function on files *)
62 let iter_file f = fold_file (fun _ line -> f line) ()
64 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
65 interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE) =
66 (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
67 Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
68 Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
69 Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@")
73 int_of_string (Sys.getenv port_env_var)
75 | Not_found -> default_port
76 | Failure "int_of_string" ->
77 prerr_endline "Warning: invalid port, reverting to default";
80 let pp_result result =
81 let result_string = MQueryUtil.text_of_result result "\n" in
82 (sprintf "<html>\n<head>\n</head>\n<body>\n<pre>%s</pre>\n</body>\n</html>"
85 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>" in
86 let bad_request body outchan =
87 Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
89 let contype = "Content-Type", "text/html" in
91 (* SEARCH ENGINE functions *)
93 let refine_constraints (x, y, z) = (x, y, z), (Some x, Some y, Some z) in
95 (* HTTP DAEMON CALLBACK *)
97 let callback (req: Http_types.request) outchan =
99 debug_print (sprintf "Received request: %s" req#path);
102 let query_string = req#param "query" in
103 let lexbuf = Lexing.from_string query_string in
104 let query = MQueryUtil.query_of_text lexbuf in
105 let result = MQueryGenerator.execute_query query in
106 let result_string = MQueryUtil.text_of_result result "\n" in
109 (sprintf "<html><body><pre>%s</pre></body></html>" result_string)
110 ~headers:[contype] outchan
112 let id = req#param "id" in
113 let result = MQueryGenerator.locate id in
114 Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
116 (let is_permitted _ = true in
117 let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
118 match req#param "url" with
119 | page when is_permitted (remove_fragment page) ->
120 Http_daemon.respond_file
121 ~fname:(sprintf "%s/%s" pages_dir (remove_fragment page)) outchan
122 | page -> Http_daemon.respond_forbidden ~url:page outchan)
123 | "/searchPattern" ->
124 let term_string = req#param "term" in
125 let lexbuf = Lexing.from_string term_string in
126 let (context, metasenv) = ([], []) in
127 let (dom, mk_metasenv_and_expr) =
128 CicTextualParserContext.main
129 ~context ~metasenv CicTextualLexer.token lexbuf
131 let id_to_uris_raw = req#param "aliases" in
132 let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
133 let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
135 | "alias" :: key :: value :: rest ->
140 Some (Disambiguate.cic_textual_parser_uri_of_string value)
143 | _ -> failwith "Can't parse aliases"
145 let parse_choices choices_raw =
146 let choices = Pcre.split ~pat:";" choices_raw in
149 match Pcre.split ~pat:"\\s" x with
151 | id::tail when id<>"" ->
154 Some (List.map (fun u -> Netencoding.Url.decode u) tail)
157 | _ -> failwith "Can't parse choices")
161 let id_to_uris = parse_tokens [] (fun _ -> None) tokens in
164 let choices_raw = req#param "choices" in
165 parse_choices choices_raw
166 with Http_types.Param_not_found _ -> (fun _ -> None)
168 let module Chat: Disambiguate.Callbacks =
171 let output_html = prerr_endline
173 let interactive_user_uri_choice
175 ?enable_button_for_non_vars ~(title: string) ~(msg: string)
176 ~(id: string) (choices: string list)
178 (match id_to_choices id with
179 | Some choices -> choices
181 let msg = Pcre.replace ~pat:"\"" ~templ:"\\\"" msg in
182 (match selection_mode with
183 | `SINGLE -> assert false
187 let formatted_choices =
189 (List.map (fun uri -> sprintf "\"%s\"" uri) choices)
193 [title_tag_RE, title;
194 choices_tag_RE, formatted_choices;
196 id_to_uris_RE, id_to_uris_raw;
200 output_string outchan processed_line)
201 interactive_user_uri_choice_TPL;
202 raise Chat_unfinished))
204 let interactive_interpretation_choice interpretations =
205 let html_interpretations_labels =
210 (String.concat "<br />"
213 (sprintf "alias %s %s" id value))
218 let html_interpretations =
226 (sprintf "alias %s %s"
228 (Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format'
238 [interpretations_RE, html_interpretations;
239 interpretations_labels_RE, html_interpretations_labels]
242 output_string outchan processed_line)
243 interactive_interpretation_choice_TPL;
244 raise Chat_unfinished
246 let input_or_locate_uri ~title =
247 UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
251 let module Disambiguate' = Disambiguate.Make (Chat) in
252 let (id_to_uris', metasenv', term') =
253 Disambiguate'.disambiguate_input
254 context metasenv dom mk_metasenv_and_expr id_to_uris
256 (match metasenv' with
258 let must = MQueryLevels2.get_constraints term' in
259 let must',only = refine_constraints must in
260 let results = MQueryGenerator.searchPattern must' only in
261 debug_print "FASE 3";
265 match id_to_uris' with
270 sprintf "\"alias %s cic:%s\""
273 | None -> assert false
275 Disambiguate.string_of_cic_textual_parser_uri
281 [results_RE, MQueryUtil.text_of_result results "\n";
282 new_aliases_RE, new_aliases]
285 output_string outchan processed_line)
287 | _ -> (* unable to instantiate some implicit variable *)
290 ~body:"some implicit variables are still unistantiated :-("
294 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
295 debug_print (sprintf "%s done!" req#path)
297 | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
298 | Http_types.Param_not_found attr_name ->
299 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
302 ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
305 printf "%s started and listening on port %d\n" daemon_name port;
306 printf "current directory is %s\n" (Sys.getcwd ());
308 Unix.putenv "http_proxy" "";
309 Mqint.set_database Mqint.postgres_db;
310 Mqint.init "host=mowgli.cs.unibo.it dbname=helm_mowgli_new_schema user=helm";
311 Http_daemon.start' ~port callback;
313 printf "%s is terminating, bye!\n" daemon_name