1 (* Copyright (C) 2002, 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 Http_common.debug := true;;
31 (* Http_common.debug := true;; *)
33 (** accepted HTTP servers for ask_uwobo method forwarding *)
34 let valid_servers = [ "mowgli.cs.unibo.it:58080" ; "mowgli.cs.unibo.it" ; "localhost:58080" ] ;;
38 let log s = debug_print s
41 module MQI = MQueryInterpreter.Make(MQICallbacks)
43 let mqi_options = "" (* default MathQL interpreter options *)
47 let daemon_name = "Search Engine";;
48 let default_port = 58085;;
49 let port_env_var = "SEARCH_ENGINE_PORT";;
53 Sys.getenv "SEARCH_ENGINE_HTML_DIR"
54 with Not_found -> "html" (* relative to searchEngine's document root *)
56 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
57 let interactive_interpretation_choice_TPL = pages_dir ^ "/templateambigpdq2.html";;
58 let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";;
60 exception Chat_unfinished
62 (** pretty print a MathQL query result to an HELM theory file *)
63 let theory_of_result result =
64 let results_no = List.length result in
65 if results_no > 0 then
66 let mode = if results_no > 10 then "linkonly" else "typeonly" in
68 let idx = ref (results_no + 1) in
72 "<tr><td valign=\"top\">" ^ string_of_int !idx ^ ".</td><td><ht:OBJECT uri=\"" ^ uri ^ "\" mode=\"" ^ mode ^ "\"/></td></tr>" ^ i
75 "<h1>Query Results:</h1><table xmlns:ht=\"http://www.cs.unibo.it/helm/namespaces/helm-theory\">" ^ results ^ "</table>"
77 "<h1>Query Results:</h1><p>No results found!</p>"
80 let pp_result result =
81 "<html xmlns:ht=\"http://www.cs.unibo.it/helm/namespaces/helm-theory\">\n<head><title>Query Results</title><style> A { text-decoration: none } </style></head>\n<body>" ^ theory_of_result result ^ "</body></html>"
84 (** chain application of Pcre substitutions *)
85 let rec apply_substs substs line =
88 | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
89 (** fold like function on files *)
90 let fold_file f init fname =
91 let inchan = open_in fname in
92 let rec fold_lines' value =
94 let line = input_line inchan in
95 fold_lines' (f value line)
96 with End_of_file -> value
98 let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
101 (** iter like function on files *)
102 let iter_file f = fold_file (fun _ line -> f line) ()
104 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
105 interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE)
107 (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
108 Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
109 Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
110 Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@")
111 let server_and_port_url_RE = Pcre.regexp "^http://([^/]+)/.*$"
113 exception NotAnInductiveDefinition
117 int_of_string (Sys.getenv port_env_var)
119 | Not_found -> default_port
120 | Failure "int_of_string" ->
121 prerr_endline "Warning: invalid port, reverting to default";
124 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>" in
125 let bad_request body outchan =
126 Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
128 let contype = "Content-Type", "text/html" in
130 (* SEARCH ENGINE functions *)
132 let refine_constraints (constr_obj, constr_rel, constr_sort) =
135 (constr_obj, constr_rel, constr_sort),
136 (Some constr_obj, Some constr_rel, Some constr_sort)
137 | "/matchConclusion" ->
140 (function (uri,pos,_) -> (uri,pos,None))
142 (function (uri,pos,depth) as constr ->
143 pos="http://www.cs.unibo.it/helm/schemas/schema-helm#MainConclusion"
145 pos="http://www.cs.unibo.it/helm/schemas/schema-helm#InConclusion"
148 (*CSC: we must select the must constraints here!!! *)
149 (constr_obj',[],[]),(Some constr_obj', None, None)
153 let get_constraints term =
155 "/locateInductivePrinciple" ->
158 Cic.MutInd (uri,t,_) -> MQueryUtil.string_of_uriref (uri,[t])
159 | _ -> raise NotAnInductiveDefinition
162 [uri,"http://www.cs.unibo.it/helm/schemas/schema-helm#InHypothesis",
164 uri,"http://www.cs.unibo.it/helm/schemas/schema-helm#MainHypothesis",
169 ["http://www.cs.unibo.it/helm/schemas/schema-helm#MainConclusion",
172 ["http://www.cs.unibo.it/helm/schemas/schema-helm#MainHypothesis",
173 Some 1, "http://www.cs.unibo.it/helm/schemas/schema-helm#Prop"]
175 (constr_obj, constr_rel, constr_sort), (None,None,None)
177 let must = MQueryLevels2.get_constraints term in
178 refine_constraints must req_path
181 (* HTTP DAEMON CALLBACK *)
183 let callback (req: Http_types.request) outchan =
185 debug_print (sprintf "Received request: %s" req#path);
186 if req#path <> "/getpage" then
187 ignore (MQI.init mqi_options);
190 let query_string = req#param "query" in
191 let lexbuf = Lexing.from_string query_string in
192 let query = MQueryUtil.query_of_text lexbuf in
193 let result = MQueryGenerator.execute_query query in
194 let result_string = pp_result result in
195 Http_daemon.respond ~body:result_string ~headers:[contype] outchan
197 let id = req#param "id" in
198 let result = MQueryGenerator.locate id in
199 Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
201 (* TODO implement "is_permitted" *)
202 (let is_permitted _ = true in
203 let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
204 let page = remove_fragment (req#param "url") in
207 bool_of_string (req#param "preprocess")
208 with Invalid_argument _ | Http_types.Param_not_found _ -> false)
211 | page when is_permitted page ->
212 (let fname = sprintf "%s/%s" pages_dir (remove_fragment page) in
213 Http_daemon.send_basic_headers ~code:200 outchan;
214 Http_daemon.send_header "Content-Type" "text/html" outchan;
215 Http_daemon.send_CRLF outchan;
216 if preprocess then begin
219 output_string outchan
222 (function (key,value) ->
224 (Pcre.extract ~pat:"param\\.(.*)" key).(1)
226 Pcre.regexp ("@" ^ key' ^ "@"), value
229 (fun (key,_) as p-> Pcre.pmatch ~pat:"^param\\." key)
236 Http_daemon.send_file ~src:(FileSrc fname) outchan)
237 | page -> Http_daemon.respond_forbidden ~url:page outchan))
239 let url = req#param "url" in
240 let server_and_port =
241 (Pcre.extract ~rex:server_and_port_url_RE url).(1)
243 if List.mem server_and_port valid_servers then
245 ~headers:["Content-Type", "text/html"]
246 ~body:(Http_client.Convenience.http_get url)
250 ~body:(pp_error ("Untrusted UWOBO server: " ^ server_and_port))
254 | "/locateInductivePrinciple" ->
255 let term_string = req#param "term" in
256 let lexbuf = Lexing.from_string term_string in
257 let (context, metasenv) = ([], []) in
258 let (dom, mk_metasenv_and_expr) =
259 CicTextualParserContext.main
260 ~context ~metasenv CicTextualLexer.token lexbuf
262 let id_to_uris_raw = req#param "aliases" in
263 let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
264 let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
266 | "alias" :: key :: value :: rest ->
267 let key' = CicTextualParser0.Id key in
273 (CicTextualParser0.Uri (MQueryMisc.cic_textual_parser_uri_of_string value))
276 | _ -> failwith "Can't parse aliases"
278 let parse_choices choices_raw =
279 let choices = Pcre.split ~pat:";" choices_raw in
282 match Pcre.split ~pat:"\\s" x with
284 | id::tail when id<>"" ->
286 prerr_endline ("#### " ^ id ^ " :=");
287 List.iter (fun u -> prerr_endline ("<" ^ Netencoding.Url.decode u ^ ">")) tail;
289 Some (List.map (fun u -> Netencoding.Url.decode u) tail)
292 | _ -> failwith "Can't parse choices")
296 let (id_to_uris : Disambiguate.domain_and_interpretation) =
297 parse_tokens [] (fun _ -> None) tokens in
300 let choices_raw = req#param "choices" in
301 parse_choices choices_raw
302 with Http_types.Param_not_found _ -> (fun _ -> None)
304 let module Chat: Disambiguate.Callbacks =
307 let get_metasenv () =
308 !CicTextualParser0.metasenv
310 let set_metasenv metasenv =
311 CicTextualParser0.metasenv := metasenv
313 let output_html = prerr_endline
315 let interactive_user_uri_choice
317 ?enable_button_for_non_vars ~(title: string) ~(msg: string)
318 ~(id: string) (choices: string list)
320 (match id_to_choices id with
321 | Some choices -> choices
323 let msg = Pcre.replace ~pat:"\"" ~templ:"\\\"" msg in
324 (match selection_mode with
325 | `SINGLE -> assert false
327 Http_daemon.send_basic_headers ~code:200 outchan ;
328 Http_daemon.send_CRLF outchan ;
331 let formatted_choices =
333 (List.map (fun uri -> sprintf "\"%s\"" uri) choices)
337 [title_tag_RE, title;
338 choices_tag_RE, formatted_choices;
340 id_to_uris_RE, id_to_uris_raw;
344 output_string outchan (processed_line ^ "\n"))
345 interactive_user_uri_choice_TPL;
346 raise Chat_unfinished))
348 let interactive_interpretation_choice interpretations =
349 let html_interpretations_labels =
354 (String.concat "<br />"
357 (sprintf "alias %s %s" id value))
362 let html_interpretations =
370 (sprintf "alias %s %s"
372 (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
378 Http_daemon.send_basic_headers ~code:200 outchan ;
379 Http_daemon.send_CRLF outchan ;
384 [interpretations_RE, html_interpretations;
385 interpretations_labels_RE, html_interpretations_labels]
388 output_string outchan (processed_line ^ "\n"))
389 interactive_interpretation_choice_TPL;
390 raise Chat_unfinished
392 let input_or_locate_uri ~title =
393 UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
397 let module Disambiguate' = Disambiguate.Make (Chat) in
398 let (id_to_uris', metasenv', term') =
399 Disambiguate'.disambiguate_input
400 context metasenv dom mk_metasenv_and_expr id_to_uris
402 (match metasenv' with
404 let must',only = get_constraints term' req#path in
405 let results = MQueryGenerator.searchPattern must' only in
406 Http_daemon.send_basic_headers ~code:200 outchan ;
407 Http_daemon.send_CRLF outchan ;
411 match id_to_uris' with
416 sprintf "\"alias %s cic:%s\""
418 CicTextualParser0.Id name -> name
419 | _ -> assert false (*CSC: completare *))
421 | None -> assert false
422 | Some (CicTextualParser0.Uri t) ->
423 MQueryMisc.string_of_cic_textual_parser_uri
425 | _ -> assert false (*CSC: completare *)))
430 [results_RE, theory_of_result results ;
431 new_aliases_RE, new_aliases]
434 output_string outchan (processed_line ^ "\n"))
436 | _ -> (* unable to instantiate some implicit variable *)
439 ~body:"some implicit variables are still unistantiated :-("
443 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
444 if req#path <> "/getpage" then
445 MQI.close mqi_options;
446 debug_print (sprintf "%s done!" req#path)
448 | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
449 | Http_types.Param_not_found attr_name ->
450 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
453 ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
456 printf "%s started and listening on port %d\n" daemon_name port;
457 printf "Current directory is %s\n" (Sys.getcwd ());
458 printf "HTML directory is %s\n" pages_dir;
460 Unix.putenv "http_proxy" "";
461 Http_daemon.start' ~port callback;
462 printf "%s is terminating, bye!\n" daemon_name