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 = "searchEngine.conf.xml" in
45 Helm_registry.load_from configuration_file
48 let port = Helm_registry.get_int "search_engine.port";;
50 let pages_dir = Helm_registry.get "search_engine.html_dir";;
52 (** accepted HTTP servers for ask_uwobo method forwarding *)
53 let valid_servers= Helm_registry.get_string_list "search_engine.valid_servers";;
55 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
56 let interactive_interpretation_choice_TPL =
57 pages_dir ^ "/templateambigpdq2.html";;
58 let constraints_choice_TPL = pages_dir ^ "/constraints_choice_template.html";;
59 (* let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";; *)
60 let final_results_TPL = pages_dir ^ "/moogle.html";;
63 let ic = Unix.open_process_in "hostname -f" in
64 let hostname = input_line ic in
65 ignore (Unix.close_process_in ic);
66 sprintf "http://%s:%d" hostname port
69 exception Chat_unfinished
70 exception Invalid_action of string (* invalid action for "/search" method *)
72 let javascript_quote s =
73 let rex = Pcre.regexp "'" in
74 let rex' = Pcre.regexp "\"" in
75 Pcre.replace ~rex ~templ:"\\'"
76 (Pcre.replace ~rex:rex' ~templ:"\\\"" s)
79 (* build a bool from a 1-character-string *)
80 let bool_of_string' = function
83 | s -> failwith ("Can't parse a boolean from string: " ^ s)
86 (* build an int option from a string *)
87 let int_of_string' = function
91 Some (int_of_string s)
92 with Failure "int_of_string" ->
93 failwith ("Can't parse an int option from string: " ^ s)
96 (* HTML pretty printers for mquery_generator types *)
98 let html_of_r_obj (pos, uri) =
100 "<tr><td><input type='checkbox' name='constr_obj' checked='on'/></td><td>%s</td><td>%s</td><td>%s</td></tr>"
101 uri (U.text_of_position pos)
102 (if U.is_main_position pos then
103 sprintf "<input name='obj_depth' size='2' type='text' value='%s' />"
104 (U.text_of_depth pos "")
106 "<input type=\"hidden\" name=\"obj_depth\" />")
109 let html_of_r_rel pos =
111 "<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>"
112 (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
115 let html_of_r_sort (pos, sort) =
117 "<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>"
118 (U.text_of_sort sort) (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
121 (** pretty print a MathQL query result to an HELM theory file *)
122 let theory_of_result result =
123 let results_no = List.length result in
124 if results_no > 0 then
125 let mode = if results_no > 10 then "linkonly" else "typeonly" in
127 let idx = ref (results_no + 1) in
129 (fun (uri,attrs) i ->
131 "<tr><td valign=\"top\">" ^ string_of_int !idx ^ ".</td><td><ht:OBJECT uri=\"" ^ uri ^ "\" mode=\"" ^ mode ^ "\"/></td></tr>" ^ i
134 "<h1>Query Results:</h1><table xmlns:ht=\"http://www.cs.unibo.it/helm/namespaces/helm-theory\">" ^ results ^ "</table>"
136 "<h1>Query Results:</h1><p>No results found!</p>"
139 let pp_result result =
140 "<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>"
143 (** chain application of Pcre substitutions *)
144 let rec apply_substs substs line =
147 | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
148 (** fold like function on files *)
149 let fold_file f init fname =
150 let inchan = open_in fname in
151 let rec fold_lines' value =
153 let line = input_line inchan in
154 fold_lines' (f value line)
155 with End_of_file -> value
157 let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
160 (** iter like function on files *)
161 let iter_file f = fold_file (fun _ line -> f line) ()
163 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
164 interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE,
165 form_RE, variables_initialization_RE, search_engine_url_RE)
167 (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
168 Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
169 Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
170 Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@", Pcre.regexp "@FORM@",
171 Pcre.regexp "@VARIABLES_INITIALIZATION@", Pcre.regexp "@SEARCH_ENGINE_URL@")
172 let server_and_port_url_RE = Pcre.regexp "^http://([^/]+)/.*$"
174 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>";;
176 let bad_request body outchan =
177 Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
180 let contype = "Content-Type", "text/html";;
182 (* SEARCH ENGINE functions *)
184 let get_constraints term =
186 | "/locateInductivePrinciple" ->
188 (CGLocateInductive.get_constraints term),
190 | "/searchPattern" ->
191 let constr_obj, constr_rel, constr_sort =
192 CGSearchPattern.get_constraints term in
193 (Some CGSearchPattern.universe),
194 (constr_obj, constr_rel, constr_sort),
195 (Some constr_obj, Some constr_rel, Some constr_sort)
196 | "/matchConclusion" ->
197 let list_of_must, only = CGMatchConclusion.get_constraints [] [] term in
198 (* FG: there is no way to choose the block number ***************************)
199 let block = pred (List.length list_of_must) in
200 (Some CGMatchConclusion.universe),
201 (List.nth list_of_must block, [], []), (Some only, None, None)
207 <must_obj> ':' <must_rel> ':' <must_sort> ':' <only_obj> ':' <only_rel> ':' <only_sort>
209 <must_*> ::= ('0'|'1') ('_'|<int>) (',' ('0'|'1') ('_'|<int>))*
212 let add_user_constraints ~constraints
213 ((obj, rel, sort), (only_obj, only_rel, only_sort))
216 let l = Pcre.split ~pat:"," s in
220 let subs = Pcre.extract ~pat:"^(.)(\\d+|_)$" s in
221 (bool_of_string' subs.(1), int_of_string' subs.(2)))
224 Not_found -> failwith ("Can't parse constraint string: " ^ constraints)
227 (* to be used on "obj" *)
228 let add_user_must33 user_must must =
230 (fun (b, i) (p, u) ->
231 if b then Some (U.set_full_position p i, u) else None)
234 (* to be used on "rel" *)
235 let add_user_must22 user_must must =
237 (fun (b, i) p -> if b then Some (U.set_main_position p i) else None)
240 (* to be used on "sort" *)
241 let add_user_must32 user_must must =
243 (fun (b, i) (p, s)-> if b then Some (U.set_main_position p i, s) else None)
246 match Pcre.split ~pat:":" constraints with
247 | [user_obj;user_rel;user_sort;user_only_obj;user_only_rel;user_only_sort] ->
249 (user_obj,user_rel,user_sort,user_only_obj,user_only_rel,user_only_sort)
251 (parse_must user_obj,
253 parse_must user_sort,
254 bool_of_string' user_only_obj,
255 bool_of_string' user_only_rel,
256 bool_of_string' user_only_sort)
259 (if user_only_obj then only_obj else None),
260 (if user_only_rel then only_rel else None),
261 (if user_only_sort then only_sort else None)
264 let rec filter_some =
267 | None::tl -> filter_some tl
268 | (Some x)::tl -> x::(filter_some tl)
270 filter_some (add_user_must33 user_obj obj),
271 filter_some (add_user_must22 user_rel rel),
272 filter_some (add_user_must32 user_sort sort)
275 | _ -> failwith ("Can't parse constraint string: " ^ constraints)
278 let send_results results
279 ?(id_to_uris = DisambiguatingParser.EnvironmentP3.of_string "") req outchan
281 Http_daemon.send_basic_headers ~code:200 outchan ;
282 Http_daemon.send_header "Content-Type" "text/xml" outchan;
283 Http_daemon.send_CRLF outchan ;
285 (search_engine_url_RE, my_own_url) ::
286 (results_RE, theory_of_result results)::
288 (function (key,value) ->
289 let key' = (Pcre.extract ~pat:"param\\.(.*)" key).(1) in
290 Pcre.regexp ("@" ^ key' ^ "@"), value)
292 (fun (key,_) as p-> Pcre.pmatch ~pat:"^param\\." key)
298 DisambiguatingParser.EnvironmentP3.to_string id_to_uris
302 (* CSC: Bug here: this is a string, not an array! *)
303 ((new_aliases_RE, "'" ^ javascript_quote new_aliases ^ "'")::subst)
306 output_string outchan (processed_line ^ "\n"))
310 (* HTTP DAEMON CALLBACK *)
312 let build_dynamic_uri url params =
314 String.concat "&" (List.map (fun (key,value) -> (key ^ "=" ^ (Netencoding.Url.encode value))) params) in
318 let build_uwobo_request (req: Http_types.request) outchan =
319 prerr_endline ("ECCOLO: " ^ req#param "param.SEARCH_ENGINE_URL");
320 let xmluri = build_dynamic_uri ((req#param "param.SEARCH_ENGINE_URL") ^ "/search") req#params in
321 prerr_endline ("xmluri: " ^ xmluri);
322 (*let xmluri = Netencoding.Url.encode xmluri in*)
323 let server_and_port = req#param "param.processorURL" in
326 (server_and_port ^ "apply")
327 (("xmluri",xmluri)::("keys",(req#param "param.thkeys"))::req#params) in
328 (* if List.mem server_and_port valid_servers then *)
329 prerr_endline newreq;
332 ~headers:["Content-Type", "text/html"]
333 ~body:(Http_client.http_get newreq)
337 ~body:(pp_error ("Untrusted UWOBO server: " ^ server_and_port ^
338 (String.concat "\n" valid_servers)))
342 let proxy url outchan =
343 let server_and_port =
344 (Pcre.extract ~rex:server_and_port_url_RE url).(1)
346 if List.mem server_and_port valid_servers then
348 ~headers:["Content-Type", "text/html"]
349 ~body:(Http_client.http_get url)
353 ~body:(pp_error ("Untrusted UWOBO server: " ^ server_and_port))
357 let callback mqi_handle (req: Http_types.request) outchan =
359 debug_print (sprintf "Received request: %s" req#path);
361 | "/help" -> Http_daemon.respond ~body:"HELM Search Engine" outchan
363 let initial_expression =
364 try req#param "expression" with Http_types.Param_not_found _ -> ""
367 Pcre.replace ~pat:"\\s*$"
368 (Pcre.replace ~pat:"^\\s*" initial_expression)
370 if expression = "" then
371 send_results [] req outchan
375 match req#param "action" with
377 prerr_endline ("EXPRESSION : " ^ expression);
378 let query = G.locate expression in
379 MQueryInterpreter.execute mqi_handle query
380 | "hint" -> failwith "NOT IMPLEMENTED" (* TODO *)
381 | "match" -> failwith "NOT IMPLEMENTED" (* TODO *)
382 | "elim" -> failwith "NOT IMPLEMENTED" (* TODO *)
383 | action -> raise (Invalid_action action)
385 send_results results req outchan
386 with Invalid_action action ->
387 Http_daemon.respond_error ~status:(`Client_error `Bad_request)
388 ~body:("Invalid action " ^ action) outchan)
390 let query_string = req#param "query" in
391 let lexbuf = Lexing.from_string query_string in
392 let query = MQueryUtil.query_of_text lexbuf in
393 let result = MQueryInterpreter.execute mqi_handle query in
394 let result_string = pp_result result in
395 Http_daemon.respond ~body:result_string ~headers:[contype] outchan
396 (* Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan *)
398 let target = req#param "target" in
399 let source = req#param "source" in
400 let query = G.unreferred target source in
401 let result = MQueryInterpreter.execute mqi_handle query in
402 Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
404 (* TODO implement "is_permitted" *)
405 (let is_permitted _ = true in
406 let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
407 let page = remove_fragment (req#param "url") in
410 bool_of_string (req#param "preprocess")
411 with Invalid_argument _ | Http_types.Param_not_found _ -> false)
414 | page when is_permitted page ->
415 (let fname = sprintf "%s/%s" pages_dir (remove_fragment page) in
416 Http_daemon.send_basic_headers ~code:200 outchan;
417 Http_daemon.send_header "Content-Type" "text/html" outchan;
418 Http_daemon.send_CRLF outchan;
419 if preprocess then begin
422 output_string outchan
424 ((search_engine_url_RE, my_own_url) ::
426 (function (key,value) ->
428 (Pcre.extract ~pat:"param\\.(.*)" key).(1)
430 Pcre.regexp ("@" ^ key' ^ "@"), value
433 (fun (key,_) as p-> Pcre.pmatch ~pat:"^param\\." key)
440 Http_daemon.send_file ~src:(FileSrc fname) outchan)
441 | page -> Http_daemon.respond_forbidden ~url:page outchan))
442 (* OLD | "/ask_uwobo" -> proxy (req#param "url") outchan *)
443 | "/ask_uwobo" -> build_uwobo_request req outchan
446 | "/locateInductivePrinciple" ->
447 let term_string = req#param "term" in
448 let (context, metasenv) = ([], []) in
449 let id_to_uris_raw = req#param "aliases" in
450 let parse_interpretation_choices choices =
451 List.map int_of_string (Pcre.split ~pat:" " choices) in
452 let parse_choices choices_raw =
453 let choices = Pcre.split ~pat:";" choices_raw in
456 match Pcre.split ~pat:"\\s" x with
458 | id::tail when id<>"" ->
461 Some (List.map (fun u -> Netencoding.Url.decode u) tail)
464 | _ -> failwith "Can't parse choices")
469 DisambiguatingParser.EnvironmentP3.of_string id_to_uris_raw in
472 let choices_raw = req#param "choices" in
473 parse_choices choices_raw
474 with Http_types.Param_not_found _ -> (fun _ -> None)
476 let interpretation_choices =
478 let choices_raw = req#param "interpretation_choices" in
479 Some (parse_interpretation_choices choices_raw)
480 with Http_types.Param_not_found _ -> None
482 let module Chat: DisambiguateTypes.Callbacks =
485 let interactive_user_uri_choice
487 ?enable_button_for_non_vars ~(title: string) ~(msg: string)
488 ~(id: string) (choices: string list)
490 (match id_to_choices id with
491 | Some choices -> choices
493 let msg = Pcre.replace ~pat:"\'" ~templ:"\\\'" msg in
494 (match selection_mode with
495 | `SINGLE -> assert false
497 Http_daemon.send_basic_headers ~code:200 outchan ;
498 Http_daemon.send_CRLF outchan ;
501 let formatted_choices =
503 (List.map (fun uri -> sprintf "\'%s\'" uri) choices)
507 [title_tag_RE, title;
508 choices_tag_RE, formatted_choices;
510 id_to_uris_RE, id_to_uris_raw;
514 output_string outchan (processed_line ^ "\n"))
515 interactive_user_uri_choice_TPL;
516 raise Chat_unfinished))
518 let interactive_interpretation_choice interpretations =
519 match interpretation_choices with
520 Some l -> prerr_endline "CARRAMBA" ; l
522 let html_interpretations_labels =
527 (String.concat "<br />"
530 let id = javascript_quote id in
531 let value = javascript_quote value in
532 sprintf "%s = %s" id value)
537 let html_interpretations =
541 | _::tl -> ("'" ^ string_of_int n ^ "'")::(aux (n+1) tl)
543 String.concat ", " (aux 0 interpretations)
545 Http_daemon.send_basic_headers ~code:200 outchan ;
546 Http_daemon.send_CRLF outchan ;
551 [interpretations_RE, html_interpretations;
552 interpretations_labels_RE, html_interpretations_labels]
555 output_string outchan (processed_line ^ "\n"))
556 interactive_interpretation_choice_TPL;
557 raise Chat_unfinished
559 let input_or_locate_uri ~title ?id () =
564 let module Disambiguate' = DisambiguatingParser.Make(Chat) in
565 let (id_to_uris', metasenv', term') =
567 Disambiguate'.disambiguate_term mqi_handle
568 context metasenv term_string id_to_uris
570 [id_to_uris',metasenv',term'] -> id_to_uris',metasenv',term'
574 ((must_obj, must_rel, must_sort) as must'),
575 ((only_obj, only_rel, only_sort) as only) =
576 get_constraints term' req#path
581 ~constraints:(req#param "constraints")
583 with Http_types.Param_not_found _ ->
585 "var aliases = '" ^ id_to_uris_raw ^ "';\n" ^
586 "var constr_obj_len = " ^
587 string_of_int (List.length must_obj) ^ ";\n" ^
588 "var constr_rel_len = " ^
589 string_of_int (List.length must_rel) ^ ";\n" ^
590 "var constr_sort_len = " ^
591 string_of_int (List.length must_sort) ^ ";\n" in
593 (if must_obj = [] then "" else
594 "<h4>Obj constraints</h4>" ^
596 (String.concat "\n" (List.map html_of_r_obj must_obj)) ^
598 (* The following three lines to make Javascript create *)
599 (* the constr_obj[] and obj_depth[] arrays even if we *)
600 (* have only one real entry. *)
601 "<input type=\"hidden\" name=\"constr_obj\" />" ^
602 "<input type=\"hidden\" name=\"obj_depth\" />") ^
603 (if must_rel = [] then "" else
604 "<h4>Rel constraints</h4>" ^
606 (String.concat "\n" (List.map html_of_r_rel must_rel)) ^
608 (* The following two lines to make Javascript create *)
609 (* the constr_rel[] and rel_depth[] arrays even if *)
610 (* we have only one real entry. *)
611 "<input type=\"hidden\" name=\"constr_rel\" />" ^
612 "<input type=\"hidden\" name=\"rel_depth\" />") ^
613 (if must_sort = [] then "" else
614 "<h4>Sort constraints</h4>" ^
616 (String.concat "\n" (List.map html_of_r_sort must_sort)) ^
618 (* The following two lines to make Javascript create *)
619 (* the constr_sort[] and sort_depth[] arrays even if *)
620 (* we have only one real entry. *)
621 "<input type=\"hidden\" name=\"constr_sort\" />" ^
622 "<input type=\"hidden\" name=\"sort_depth\" />") ^
623 "<h4>Only constraints</h4>" ^
624 "Enforce Only constraints for objects: " ^
625 "<input type='checkbox' name='only_obj'" ^
626 (if only_obj = None then "" else " checked='yes'") ^ " /><br />" ^
627 "Enforce Rel constraints for objects: " ^
628 "<input type='checkbox' name='only_rel'" ^
629 (if only_rel = None then "" else " checked='yes'") ^ " /><br />" ^
630 "Enforce Sort constraints for objects: " ^
631 "<input type='checkbox' name='only_sort'" ^
632 (if only_sort = None then "" else " checked='yes'") ^ " /><br />"
634 Http_daemon.send_basic_headers ~code:200 outchan ;
635 Http_daemon.send_CRLF outchan ;
641 variables_initialization_RE, variables] line
643 output_string outchan (processed_line ^ "\n"))
644 constraints_choice_TPL;
645 raise Chat_unfinished)
648 G.query_of_constraints universe must'' only'
650 let results = MQueryInterpreter.execute mqi_handle query in
651 send_results results ~id_to_uris:id_to_uris' req outchan
653 Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
654 debug_print (sprintf "%s done!" req#path)
656 | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
657 | Http_types.Param_not_found attr_name ->
658 bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
660 let msg = sprintf "Uncaught exception: %s" (Printexc.to_string exc) in
662 Http_daemon.respond ~body:(pp_error msg) outchan
664 printf "%s started and listening on port %d\n" daemon_name port;
665 printf "Current directory is %s\n" (Sys.getcwd ());
666 printf "HTML directory is %s\n" pages_dir;
668 Unix.putenv "http_proxy" "";
669 let mqi_handle = C.init ~log:debug_print () in
670 Http_daemon.start' ~port (callback mqi_handle);
672 printf "%s is terminating, bye!\n" daemon_name