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/.
28 module G = MQueryGenerator
34 let debug_print s = if debug then prerr_endline s;;
35 Http_common.debug := true;;
36 (* Http_common.debug := true;; *)
40 let daemon_name = "Search Engine";;
42 (* First of all we load the configuration *)
44 let configuration_file = "/projects/helm/etc/searchEngine.conf.xml" in
45 Helm_registry.load_from configuration_file
48 let pages_dir = Helm_registry.get "search_engine.html_dir";;
50 (** accepted HTTP servers for ask_uwobo method forwarding *)
51 let valid_servers= Helm_registry.get_string_list "search_engine.valid_servers";;
54 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
55 let interactive_interpretation_choice_TPL =
56 pages_dir ^ "/templateambigpdq2.html";;
57 let constraints_choice_TPL = pages_dir ^ "/constraints_choice_template.html";;
58 let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";;
60 exception Chat_unfinished
62 (* build a bool from a 1-character-string *)
63 let bool_of_string' = function
66 | s -> failwith ("Can't parse a boolean from string: " ^ s)
69 (* build an int option from a string *)
70 let int_of_string' = function
74 Some (int_of_string s)
75 with Failure "int_of_string" ->
76 failwith ("Can't parse an int option from string: " ^ s)
79 (* HTML pretty printers for mquery_generator types *)
81 let html_of_r_obj (pos, uri) =
83 "<tr><td><input type='checkbox' name='constr_obj' checked='on'/></td><td>%s</td><td>%s</td><td>%s</td></tr>"
84 uri (U.text_of_position pos)
85 (if U.is_main_position pos then
86 sprintf "<input name='obj_depth' size='2' type='text' value='%s' />"
87 (U.text_of_depth pos "")
89 "<input type=\"hidden\" name=\"obj_depth\" />")
92 let html_of_r_rel pos =
94 "<tr><td><input type='checkbox' name='constr_rel' checked='on'/></td><td>%s</td><td><input name='rel_depth' size='2' type='text' value='%s' /></td></tr>"
95 (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
98 let html_of_r_sort (pos, sort) =
100 "<tr><td><input type='checkbox' name='constr_sort' checked='on'/></td><td>%s</td><td>%s</td><td><input name='sort_depth' size='2' type='text' value='%s'/></td></tr>"
101 (U.text_of_sort sort) (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
104 (** pretty print a MathQL query result to an HELM theory file *)
105 let theory_of_result result =
106 let results_no = List.length result in
107 if results_no > 0 then
108 let mode = if results_no > 10 then "linkonly" else "typeonly" in
110 let idx = ref (results_no + 1) in
112 (fun (uri,attrs) i ->
114 "<tr><td valign=\"top\">" ^ string_of_int !idx ^ ".</td><td><ht:OBJECT uri=\"" ^ uri ^ "\" mode=\"" ^ mode ^ "\"/></td></tr>" ^ i
117 "<h1>Query Results:</h1><table xmlns:ht=\"http://www.cs.unibo.it/helm/namespaces/helm-theory\">" ^ results ^ "</table>"
119 "<h1>Query Results:</h1><p>No results found!</p>"
122 let pp_result result =
123 "<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>"
126 (** chain application of Pcre substitutions *)
127 let rec apply_substs substs line =
130 | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
131 (** fold like function on files *)
132 let fold_file f init fname =
133 let inchan = open_in fname in
134 let rec fold_lines' value =
136 let line = input_line inchan in
137 fold_lines' (f value line)
138 with End_of_file -> value
140 let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
143 (** iter like function on files *)
144 let iter_file f = fold_file (fun _ line -> f line) ()
146 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
147 interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE,
148 form_RE, variables_initialization_RE)
150 (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
151 Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
152 Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
153 Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@", Pcre.regexp "@FORM@",
154 Pcre.regexp "@VARIABLES_INITIALIZATION@")
155 let server_and_port_url_RE = Pcre.regexp "^http://([^/]+)/.*$"
157 let port = Helm_registry.get_int "search_engine.port";;
159 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>";;
161 let bad_request body outchan =
162 Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
165 let contype = "Content-Type", "text/html";;
167 (* SEARCH ENGINE functions *)
169 let get_constraints term =
171 | "/locateInductivePrinciple" ->
173 (CGLocateInductive.get_constraints term),
175 | "/searchPattern" ->
176 let constr_obj, constr_rel, constr_sort =
177 CGSearchPattern.get_constraints term in
178 (Some CGSearchPattern.universe),
179 (constr_obj, constr_rel, constr_sort),
180 (Some constr_obj, Some constr_rel, Some constr_sort)
181 | "/matchConclusion" ->
182 let list_of_must, only = CGMatchConclusion.get_constraints [] [] term in
183 (* FG: there is no way to choose the block number ***************************)
184 let block = pred (List.length list_of_must) in
185 (Some CGMatchConclusion.universe),
186 (List.nth list_of_must block, [], []), (Some only, None, None)
192 <must_obj> ':' <must_rel> ':' <must_sort> ':' <only_obj> ':' <only_rel> ':' <only_sort>
194 <must_*> ::= ('0'|'1') ('_'|<int>) (',' ('0'|'1') ('_'|<int>))*
197 let add_user_constraints ~constraints
198 ((obj, rel, sort), (only_obj, only_rel, only_sort))
201 let l = Pcre.split ~pat:"," s in
205 let subs = Pcre.extract ~pat:"^(.)(\\d+|_)$" s in
206 (bool_of_string' subs.(1), int_of_string' subs.(2)))
209 Not_found -> failwith ("Can't parse constraint string: " ^ constraints)
212 (* to be used on "obj" *)
213 let add_user_must33 user_must must =
215 (fun (b, i) (p, u) ->
216 if b then Some (U.set_full_position p i, u) else None)
219 (* to be used on "rel" *)
220 let add_user_must22 user_must must =
222 (fun (b, i) p -> if b then Some (U.set_main_position p i) else None)
225 (* to be used on "sort" *)
226 let add_user_must32 user_must must =
228 (fun (b, i) (p, s)-> if b then Some (U.set_main_position p i, s) else None)
231 match Pcre.split ~pat:":" constraints with
232 | [user_obj;user_rel;user_sort;user_only_obj;user_only_rel;user_only_sort] ->
234 (user_obj,user_rel,user_sort,user_only_obj,user_only_rel,user_only_sort)
236 (parse_must user_obj,
238 parse_must user_sort,
239 bool_of_string' user_only_obj,
240 bool_of_string' user_only_rel,
241 bool_of_string' user_only_sort)
244 (if user_only_obj then only_obj else None),
245 (if user_only_rel then only_rel else None),
246 (if user_only_sort then only_sort else None)
249 let rec filter_some =
252 | None::tl -> filter_some tl
253 | (Some x)::tl -> x::(filter_some tl)
255 filter_some (add_user_must33 user_obj obj),
256 filter_some (add_user_must22 user_rel rel),
257 filter_some (add_user_must32 user_sort sort)
260 | _ -> failwith ("Can't parse constraint string: " ^ constraints)
263 (* HTTP DAEMON CALLBACK *)
265 let callback mqi_handle (req: Http_types.request) outchan =
267 debug_print (sprintf "Received request: %s" req#path);
270 let query_string = req#param "query" in
271 let lexbuf = Lexing.from_string query_string in
272 let query = MQueryUtil.query_of_text lexbuf in
273 let result = MQueryInterpreter.execute mqi_handle query in
274 let result_string = pp_result result in
275 Http_daemon.respond ~body:result_string ~headers:[contype] outchan
277 let id = req#param "id" in
278 let query = G.locate id in
279 let result = MQueryInterpreter.execute mqi_handle query in
280 Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
282 let target = req#param "target" in
283 let source = req#param "source" in
284 let query = G.unreferred target source in
285 let result = MQueryInterpreter.execute mqi_handle query in
286 Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
288 (* TODO implement "is_permitted" *)
289 (let is_permitted _ = true in
290 let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
291 let page = remove_fragment (req#param "url") in
294 bool_of_string (req#param "preprocess")
295 with Invalid_argument _ | Http_types.Param_not_found _ -> false)
298 | page when is_permitted page ->
299 (let fname = sprintf "%s/%s" pages_dir (remove_fragment page) in
300 Http_daemon.send_basic_headers ~code:200 outchan;
301 Http_daemon.send_header "Content-Type" "text/html" outchan;
302 Http_daemon.send_CRLF outchan;
303 if preprocess then begin
306 output_string outchan
309 (function (key,value) ->
311 (Pcre.extract ~pat:"param\\.(.*)" key).(1)
313 Pcre.regexp ("@" ^ key' ^ "@"), value
316 (fun (key,_) as p-> Pcre.pmatch ~pat:"^param\\." key)
323 Http_daemon.send_file ~src:(FileSrc fname) outchan)
324 | page -> Http_daemon.respond_forbidden ~url:page outchan))
326 let url = req#param "url" in
327 let server_and_port =
328 (Pcre.extract ~rex:server_and_port_url_RE url).(1)
330 if List.mem server_and_port valid_servers then
332 ~headers:["Content-Type", "text/html"]
333 ~body:(Http_client.http_get url)
337 ~body:(pp_error ("Untrusted UWOBO server: " ^ server_and_port))
341 | "/locateInductivePrinciple" ->
342 let term_string = req#param "term" in
343 let (context, metasenv) = ([], []) in
344 let id_to_uris_raw = req#param "aliases" in
346 let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
347 let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
349 | "alias" :: key :: value :: rest ->
350 let key' = CicTextualParser0.Id key in
356 (CicTextualParser0.Uri (MQueryMisc.cic_textual_parser_uri_of_string value))
359 | _ -> failwith "Can't parse aliases"
362 let parse_choices choices_raw =
363 let choices = Pcre.split ~pat:";" choices_raw in
366 match Pcre.split ~pat:"\\s" x with
368 | id::tail when id<>"" ->
371 Some (List.map (fun u -> Netencoding.Url.decode u) tail)
374 | _ -> failwith "Can't parse choices")
379 DisambiguatingParser.EnvironmentP3.of_string id_to_uris_raw in
380 print_endline ("id_to_uris_raw: " ^ id_to_uris_raw) ;
381 print_endline ("id_to_uris: " ^ (DisambiguatingParser.EnvironmentP3.to_string id_to_uris)) ;
384 let choices_raw = req#param "choices" in
385 parse_choices choices_raw
386 with Http_types.Param_not_found _ -> (fun _ -> None)
388 let module Chat: DisambiguateTypes.Callbacks =
391 let interactive_user_uri_choice
393 ?enable_button_for_non_vars ~(title: string) ~(msg: string)
394 ~(id: string) (choices: string list)
396 (match id_to_choices id with
397 | Some choices -> choices
399 let msg = Pcre.replace ~pat:"\'" ~templ:"\\\'" msg in
400 (match selection_mode with
401 | `SINGLE -> assert false
403 Http_daemon.send_basic_headers ~code:200 outchan ;
404 Http_daemon.send_CRLF outchan ;
407 let formatted_choices =
409 (List.map (fun uri -> sprintf "\'%s\'" uri) choices)
413 [title_tag_RE, title;
414 choices_tag_RE, formatted_choices;
416 id_to_uris_RE, id_to_uris_raw;
420 output_string outchan (processed_line ^ "\n"))
421 interactive_user_uri_choice_TPL;
422 raise Chat_unfinished))
424 let interactive_interpretation_choice interpretations =
425 let html_interpretations_labels =
430 (String.concat "<br />"
433 (sprintf "alias id %s = %s" id value))
438 let html_interpretations =
446 (sprintf "alias id %s = %s"
448 (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
454 Http_daemon.send_basic_headers ~code:200 outchan ;
455 Http_daemon.send_CRLF outchan ;
460 [interpretations_RE, html_interpretations;
461 interpretations_labels_RE, html_interpretations_labels]
464 output_string outchan (processed_line ^ "\n"))
465 interactive_interpretation_choice_TPL;
466 raise Chat_unfinished
468 let input_or_locate_uri ~title =
469 UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
473 let module Disambiguate' = DisambiguatingParser.Make(Chat) in
474 let (id_to_uris', metasenv', term') =
475 Disambiguate'.disambiguate_term mqi_handle
476 context metasenv term_string id_to_uris
478 (match metasenv' with
481 ((must_obj, must_rel, must_sort) as must'),
482 ((only_obj, only_rel, only_sort) as only) =
483 get_constraints term' req#path
488 ~constraints:(req#param "constraints")
490 with Http_types.Param_not_found _ ->
492 "var aliases = '" ^ id_to_uris_raw ^ "';\n" ^
493 "var constr_obj_len = " ^
494 string_of_int (List.length must_obj) ^ ";\n" ^
495 "var constr_rel_len = " ^
496 string_of_int (List.length must_rel) ^ ";\n" ^
497 "var constr_sort_len = " ^
498 string_of_int (List.length must_sort) ^ ";\n" in
500 (if must_obj = [] then "" else
501 "<h4>Obj constraints</h4>" ^
503 (String.concat "\n" (List.map html_of_r_obj must_obj)) ^
505 (* The following three lines to make Javascript create *)
506 (* the constr_obj[] and obj_depth[] arrays even if we *)
507 (* have only one real entry. *)
508 "<input type=\"hidden\" name=\"constr_obj\" />" ^
509 "<input type=\"hidden\" name=\"obj_depth\" />") ^
510 (if must_rel = [] then "" else
511 "<h4>Rel constraints</h4>" ^
513 (String.concat "\n" (List.map html_of_r_rel must_rel)) ^
515 (* The following two lines to make Javascript create *)
516 (* the constr_rel[] and rel_depth[] arrays even if *)
517 (* we have only one real entry. *)
518 "<input type=\"hidden\" name=\"constr_rel\" />" ^
519 "<input type=\"hidden\" name=\"rel_depth\" />") ^
520 (if must_sort = [] then "" else
521 "<h4>Sort constraints</h4>" ^
523 (String.concat "\n" (List.map html_of_r_sort must_sort)) ^
525 (* The following two lines to make Javascript create *)
526 (* the constr_sort[] and sort_depth[] arrays even if *)
527 (* we have only one real entry. *)
528 "<input type=\"hidden\" name=\"constr_sort\" />" ^
529 "<input type=\"hidden\" name=\"sort_depth\" />") ^
530 "<h4>Only constraints</h4>" ^
531 "Enforce Only constraints for objects: " ^
532 "<input type='checkbox' name='only_obj'" ^
533 (if only_obj = None then "" else " checked='yes'") ^ " /><br />" ^
534 "Enforce Rel constraints for objects: " ^
535 "<input type='checkbox' name='only_rel'" ^
536 (if only_rel = None then "" else " checked='yes'") ^ " /><br />" ^
537 "Enforce Sort constraints for objects: " ^
538 "<input type='checkbox' name='only_sort'" ^
539 (if only_sort = None then "" else " checked='yes'") ^ " /><br />"
541 Http_daemon.send_basic_headers ~code:200 outchan ;
542 Http_daemon.send_CRLF outchan ;
548 variables_initialization_RE, variables] line
550 output_string outchan (processed_line ^ "\n"))
551 constraints_choice_TPL;
552 raise Chat_unfinished)
555 G.query_of_constraints universe must'' only'
557 let results = MQueryInterpreter.execute mqi_handle query in
558 Http_daemon.send_basic_headers ~code:200 outchan ;
559 Http_daemon.send_CRLF outchan ;
563 DisambiguatingParser.EnvironmentP3.to_string id_to_uris' in
565 match id_to_uris' with
570 sprintf "\'alias %s cic:%s\'"
572 CicTextualParser0.Id name -> name
573 | _ -> assert false (*CSC: completare *))
575 | None -> assert false
576 | Some (CicTextualParser0.Uri t) ->
577 MQueryMisc.string_of_cic_textual_parser_uri
579 | _ -> assert false (*CSC: completare *)))
585 [results_RE, theory_of_result results ;
586 new_aliases_RE, new_aliases]
589 output_string outchan (processed_line ^ "\n"))
591 | _ -> (* unable to instantiate some implicit variable *)
594 ~body:"some implicit variables are still unistantiated :-("
597 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
598 debug_print (sprintf "%s done!" req#path)
600 | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
601 | Http_types.Param_not_found attr_name ->
602 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
605 ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
608 printf "%s started and listening on port %d\n" daemon_name port;
609 printf "Current directory is %s\n" (Sys.getcwd ());
610 printf "HTML directory is %s\n" pages_dir;
612 Unix.putenv "http_proxy" "";
613 let mqi_handle = C.init ~log:debug_print () in
614 Http_daemon.start' ~port (callback mqi_handle);
616 printf "%s is terminating, bye!\n" daemon_name