1 (* Copyright (C) 2002-2005, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://cs.unibo.it/helm/.
29 let debug_print s = if debug then prerr_endline s
30 let _ = Http_common.debug := false
32 exception Chat_unfinished
33 exception Unbound_identifier of string
34 exception Invalid_action of string (* invalid action for "/search" method *)
36 (** raised by elim when a MutInd is required but not found *)
37 exception Not_a_MutInd
39 let daemon_name = "Moogle"
40 let configuration_file = "/projects/helm/etc/moogle.conf.xml"
43 "ACTION"; "ADVANCED"; "ADVANCED_CHECKED"; "CHOICES"; "CURRENT_CHOICES";
44 "EXPRESSION"; "ID"; "IDEN"; "ID_TO_URIS"; "INTERPRETATIONS";
45 "INTERPRETATIONS_LABELS"; "MSG"; "NEW_ALIASES"; "NEXT_LINK"; "NO_CHOICES";
46 "PAGE"; "PAGES"; "PREV_LINK"; "QUERY_KIND"; "QUERY_SUMMARY"; "RESULTS";
47 "SEARCH_ENGINE_URL"; "SIMPLE_CHECKED"; "TITLE";
51 let regexps = Hashtbl.create 25 in
53 (fun tag -> Hashtbl.add regexps tag (Pcre.regexp (sprintf "@%s@" tag)))
57 Hashtbl.find regexps name
58 with Not_found -> assert false
60 (* First of all we load the configuration *)
61 let _ = Helm_registry.load_from configuration_file
62 let port = Helm_registry.get_int "search_engine.port"
63 let pages_dir = Helm_registry.get "search_engine.html_dir"
65 let moogle_TPL = pages_dir ^ "/moogle.html"
66 let choices_TPL = pages_dir ^ "/moogle_chat.html"
69 let ic = Unix.open_process_in "hostname -f" in
70 let hostname = input_line ic in
71 ignore (Unix.close_process_in ic);
72 sprintf "http://%s:%d" hostname port
73 let _ = Helm_registry.set "search_engine.my_own_url" my_own_url
75 let bad_request body outchan =
76 Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) ~body
79 (** chain application of Pcre substitutions *)
80 let rec apply_substs substs line =
83 | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
84 (** fold like function on files *)
85 let fold_file f init fname =
86 let inchan = open_in fname in
87 let rec fold_lines' value =
89 let line = input_line inchan in
90 fold_lines' (f value line)
91 with End_of_file -> value
93 let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
96 (** iter like function on files *)
97 let iter_file f = fold_file (fun _ line -> f line) ()
98 let javascript_quote s =
99 let rex = Pcre.regexp "'" in
100 let rex' = Pcre.regexp "\"" in
101 Pcre.replace ~rex ~templ:"\\'"
102 (Pcre.replace ~rex:rex' ~templ:"\\\"" s)
104 let len = String.length s in
105 String.sub s 1 (len-1)
107 let len = String.length s in
108 let suffix = String.sub s (len-4) 4 in
109 not (suffix = ".var")
111 let add_param_substs params =
114 let key' = (Pcre.extract ~pat:"param\\.(.*)" key).(1) in
115 Pcre.regexp ("@" ^ key' ^ "@"), value)
117 (fun ((key,_) as p) -> Pcre.pmatch ~pat:"^param\\." key)
120 let page_RE = Pcre.regexp "¶m\\.page=\\d+"
121 let identifier_RE = Pcre.regexp "^\\s*\\w+\\s*$"
123 let query_kind_of_req (req: Http_types.request) =
125 | "/match" -> "Match"
127 | "/locate" -> "Locate"
131 (* given a uri with a query part in input try to find in it a string
132 * "¶m_name=..." (where param_name is given). If found its value will be
133 * set to param_value. If not, a trailing "¶m_name=param_value" (where
134 * both are given) is added to the input string *)
135 let patch_param param_name param_value url =
136 let rex = Pcre.regexp (sprintf "&%s=[^&]*" (Pcre.quote param_name)) in
137 if Pcre.pmatch ~rex url then
138 Pcre.replace ~rex ~templ:(sprintf "%s=%s" param_name param_value) url
140 sprintf "%s&%s=%s" url param_name param_value
142 (** HTML encoding, e.g.: "<" -> "<" *)
143 let html_encode = Netencoding.Html.encode_from_latin1
145 let send_results results
146 ?(id_to_uris = CicTextualParser2.EnvironmentP3.of_string "")
147 (req: Http_types.request) outchan
149 let query_kind = query_kind_of_req req in
150 let interp = try req#param "interp" with Http_types.Param_not_found _ -> "" in
151 let page_link anchor page =
153 let this = req#param "this" in
155 (patch_param "param.interp" interp
156 (patch_param "param.page" (string_of_int page)
159 let target = Pcre.replace ~pat:"&" ~templ:"&" target in
160 sprintf "<a href=\"%s\">%s</a>" target anchor
161 with Http_types.Param_not_found _ -> ""
163 Http_daemon.send_basic_headers ~code:(`Code 200) outchan ;
164 Http_daemon.send_header "Content-Type" "text/xml" outchan;
165 Http_daemon.send_CRLF outchan ;
168 | `Results results ->
169 let page = try int_of_string (req#param "page") with _ -> 1 in
170 let results_no = List.length results in
171 let results_per_page =
172 Helm_registry.get_int "search_engine.results_per_page"
175 if results_no mod results_per_page = 0 then
176 results_no / results_per_page
178 results_no / results_per_page + 1
180 let pages = if pages = 0 then 1 else pages in
181 let (summary, results) = MooglePp.theory_of_result page results in
182 [ tag "PAGE", string_of_int page;
183 tag "PAGES", string_of_int pages;
184 tag "PREV_LINK", (if page > 1 then page_link "Prev" (page-1) else "");
186 (if page < pages then page_link "Next" (page+1) else "");
187 tag "QUERY_KIND", query_kind;
188 tag "QUERY_SUMMARY", summary;
189 tag "RESULTS", results ]
195 tag "QUERY_KIND", query_kind;
196 tag "QUERY_SUMMARY", "error";
202 with Http_types.Param_not_found _ -> "no"
205 (tag "SEARCH_ENGINE_URL", my_own_url) ::
206 (tag "ADVANCED", advanced) ::
207 (tag "EXPRESSION", html_encode (req#param "expression")) ::
208 add_param_substs req#params @
209 (if advanced = "no" then
210 [ tag "SIMPLE_CHECKED", "checked='true'";
211 tag "ADVANCED_CHECKED", "" ]
213 [ tag "SIMPLE_CHECKED", "";
214 tag "ADVANCED_CHECKED", "checked='true'" ]) @
220 CicTextualParser2.EnvironmentP3.to_string id_to_uris
224 (* CSC: Bug here: this is a string, not an array! *)
225 ((tag "NEW_ALIASES", "'" ^ javascript_quote new_aliases ^ "'") ::
229 output_string outchan (processed_line ^ "\n"))
232 let exec_action dbd (req: Http_types.request) outchan =
233 let term_str = req#param "expression" in
235 if req#path = "/elim" && not (Pcre.pmatch ~rex:identifier_RE term_str) then
237 let (context, metasenv) = ([], []) in
239 try req#param "aliases"
240 with Http_types.Param_not_found _ -> ""
242 let parse_interpretation_choices choices =
243 List.map int_of_string (Pcre.split ~pat:" " choices) in
244 let parse_choices choices_raw =
245 let choices = Pcre.split ~pat:";" choices_raw in
248 match Pcre.split ~pat:"\\s" x with
250 | id::tail when id<>"" ->
253 Some (List.map (fun u -> Netencoding.Url.decode u) tail)
256 | _ -> failwith "Can't parse choices")
260 let id_to_uris = CicTextualParser2.EnvironmentP3.of_string id_to_uris_raw in
263 parse_choices (req#param "choices")
264 with Http_types.Param_not_found _ -> (fun _ -> None)
266 let interpretation_choices =
268 let choices_raw = req#param "interpretation_choices" in
269 if choices_raw = "" then None
270 else Some (parse_interpretation_choices choices_raw)
271 with Http_types.Param_not_found _ -> None
273 let module Chat: DisambiguateTypes.Callbacks =
275 let interactive_user_uri_choice ~selection_mode ?ok
276 ?enable_button_for_non_vars ~(title: string) ~(msg: string)
277 ~(id: string) (choices: string list)
279 match id_to_choices id with
280 | Some choices -> choices
281 | None -> List.filter nonvar choices
283 let interactive_interpretation_choice interpretations =
284 match interpretation_choices with
287 let html_interpretations =
288 MooglePp.html_of_interpretations interpretations
290 Http_daemon.send_basic_headers ~code:(`Code 200) outchan ;
291 Http_daemon.send_CRLF outchan ;
295 with Http_types.Param_not_found _ -> "no"
297 let query_kind = query_kind_of_req req in
302 [ tag "SEARCH_ENGINE_URL", my_own_url;
303 tag "ADVANCED", advanced;
304 tag "INTERPRETATIONS", html_interpretations;
305 tag "CURRENT_CHOICES", req#param "choices";
306 tag "EXPRESSION", html_encode (req#param "expression");
307 tag "QUERY_KIND", query_kind;
308 tag "QUERY_SUMMARY", "disambiguation";
309 tag "ACTION", string_tail req#path ]
312 output_string outchan (processed_line ^ "\n"))
314 raise Chat_unfinished
316 let input_or_locate_uri ~title ?id () =
318 | Some id -> raise (Unbound_identifier id)
319 | None -> assert false
322 let module Disambiguate' = Disambiguate.Make(Chat) in
323 let ast = CicTextualParser2.parse_term (Stream.of_string term_str) in
324 let (id_to_uris, metasenv, term) =
326 Disambiguate'.disambiguate_term dbd context metasenv ast id_to_uris
328 | [id_to_uris,metasenv,term,_] -> id_to_uris,metasenv,term
333 | "/match" -> MetadataQuery.match_term ~dbd term
335 let status = ProofEngineTypes.initial_status term metasenv in
336 let intros = PrimitiveTactics.intros_tac () in
337 let subgoals = ProofEngineTypes.apply_tactic intros status in
340 let (uri,metasenv,bo,ty) = proof in
341 List.map fst (MetadataQuery.hint ~dbd (proof, goal))
346 | Cic.MutInd (uri, typeno, _) ->
347 UriManager.string_of_uriref (uri, [typeno])
348 | _ -> raise Not_a_MutInd
350 MetadataQuery.elim ~dbd uri
353 send_results ~id_to_uris (`Results uris) req outchan
356 send_results (`Error (MooglePp.pp_error "Not an inductive type"
357 ("elim requires as input an identifier corresponding to an inductive"
361 let callback dbd (req: Http_types.request) outchan =
363 debug_print (sprintf "Received request: %s" req#path);
366 (* TODO implement "is_permitted" *)
367 (let is_permitted page = not (Pcre.pmatch ~pat:"/" page) in
368 let page = req#param "url" in
369 let fname = sprintf "%s/%s" pages_dir page in
372 bool_of_string (req#param "preprocess")
373 with Invalid_argument _ | Http_types.Param_not_found _ -> false)
376 | page when is_permitted page && Sys.file_exists fname ->
377 Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
378 Http_daemon.send_header "Content-Type" "text/html" outchan;
379 Http_daemon.send_CRLF outchan;
380 if preprocess then begin
383 output_string outchan
385 ((tag "SEARCH_ENGINE_URL", my_own_url) ::
386 (tag "ADVANCED", "no") ::
387 (tag "RESULTS", "") ::
388 add_param_substs req#params)
393 Http_daemon.send_file ~src:(Http_types.FileSrc fname) outchan
394 | page -> Http_daemon.respond_forbidden ~url:page outchan))
395 | "/help" -> Http_daemon.respond ~body:daemon_name outchan
397 let initial_expression =
398 try req#param "expression" with Http_types.Param_not_found _ -> ""
401 Pcre.replace ~pat:"\\s*$"
402 (Pcre.replace ~pat:"^\\s*" initial_expression)
404 if expression = "" then
405 send_results (`Results []) req outchan
407 let results = MetadataQuery.locate ~dbd expression in
408 send_results (`Results results) req outchan
412 | "/match" -> exec_action dbd req outchan
414 Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request))
416 debug_print (sprintf "%s done!" req#path)
418 | Chat_unfinished -> ()
419 | Http_types.Param_not_found attr_name ->
420 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
421 | CicTextualParser2.Parse_error (_, msg) ->
422 send_results (`Error (MooglePp.pp_error "Parse error" msg)) req outchan
423 | Unbound_identifier id ->
424 send_results (`Error (MooglePp.pp_error "Unbound identifier" id)) req
427 let exn_string = Printexc.to_string exn in
428 debug_print exn_string;
429 let msg = MooglePp.pp_error "Uncaught exception" exn_string in
430 send_results (`Error msg) req outchan
432 let restore_environment () =
434 Helm_registry.get_opt Helm_registry.get "search_engine.environment_dump"
438 printf "Restoring Cic environment from %s ... " fname; flush stdout;
439 let ic = open_in fname in
440 CicEnvironment.restore_from_channel ic;
442 printf "done!\n"; flush stdout
445 printf "%s started and listening on port %d\n" daemon_name port;
446 printf "Current directory is %s\n" (Sys.getcwd ());
447 printf "HTML directory is %s\n" pages_dir;
449 Unix.putenv "http_proxy" "";
452 ~host:(Helm_registry.get "db.host")
453 ~database:(Helm_registry.get "db.database")
454 ~user:(Helm_registry.get "db.user")
457 restore_environment ();
458 Http_daemon.start' ~port (callback dbd);
459 printf "%s is terminating, bye!\n" daemon_name