]> matita.cs.unibo.it Git - helm.git/blob - helm/searchEngine/searchEngine.ml
- new pretty printing of interpretations
[helm.git] / helm / searchEngine / searchEngine.ml
1 (* Copyright (C) 2002-2005, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 open Printf
27
28 let debug = true
29 let debug_print s = if debug then prerr_endline s
30 let _ = Http_common.debug := false
31
32 exception Chat_unfinished
33 exception Unbound_identifier of string
34 exception Invalid_action of string  (* invalid action for "/search" method *)
35
36 let daemon_name = "Moogle"
37 let configuration_file = "/projects/helm/etc/moogle.conf.xml"
38
39 let placeholders = [
40   "ACTION"; "ADVANCED"; "ADVANCED_CHECKED"; "CHOICES"; "CURRENT_CHOICES";
41   "EXPRESSION"; "ID"; "IDEN"; "ID_TO_URIS"; "INTERPRETATIONS";
42   "INTERPRETATIONS_LABELS"; "MSG"; "NEW_ALIASES"; "NEXT_LINK"; "NO_CHOICES";
43   "PAGE"; "PAGES"; "PREV_LINK"; "QUERY_KIND"; "QUERY_SUMMARY"; "RESULTS";
44   "SEARCH_ENGINE_URL"; "SIMPLE_CHECKED"; "TITLE";
45 ]
46
47 let tag =
48   let regexps = Hashtbl.create 25 in
49   List.iter
50     (fun tag -> Hashtbl.add regexps tag (Pcre.regexp (sprintf "@%s@" tag)))
51     placeholders;
52   fun name ->
53     try
54       Hashtbl.find regexps name
55     with Not_found -> assert false
56
57   (* First of all we load the configuration *)
58 let _ = Helm_registry.load_from configuration_file
59 let port = Helm_registry.get_int "search_engine.port"
60 let pages_dir = Helm_registry.get "search_engine.html_dir"
61
62 let moogle_TPL = pages_dir ^ "/moogle.html"
63 let choices_TPL = pages_dir ^ "/moogle_chat.html"
64
65 let my_own_url =
66  let ic = Unix.open_process_in "hostname -f" in
67  let hostname = input_line ic in
68  ignore (Unix.close_process_in ic);
69  sprintf "http://%s:%d" hostname port
70 let _ = Helm_registry.set "search_engine.my_own_url" my_own_url
71
72 let bad_request body outchan =
73   Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request)) ~body
74     outchan
75
76   (** chain application of Pcre substitutions *)
77 let rec apply_substs substs line =
78   match substs with
79   | [] -> line
80   | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
81   (** fold like function on files *)
82 let fold_file f init fname =
83   let inchan = open_in fname in
84   let rec fold_lines' value =
85     try 
86       let line = input_line inchan in 
87       fold_lines' (f value line)
88     with End_of_file -> value
89   in
90   let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
91   close_in inchan;
92   res
93   (** iter like function on files *)
94 let iter_file f = fold_file (fun _ line -> f line) ()
95 let javascript_quote s =
96  let rex = Pcre.regexp "'" in
97  let rex' = Pcre.regexp "\"" in
98   Pcre.replace ~rex ~templ:"\\'"
99    (Pcre.replace ~rex:rex' ~templ:"\\\"" s)
100 let string_tail s =
101   let len = String.length s in
102   String.sub s 1 (len-1)
103 let nonvar s =
104   let len = String.length s in
105   let suffix = String.sub s (len-4) 4 in
106   not (suffix  = ".var")
107
108 let add_param_substs params =
109   List.map
110     (fun (key,value) ->
111       let key' = (Pcre.extract ~pat:"param\\.(.*)" key).(1) in
112       Pcre.regexp ("@" ^ key' ^ "@"), value)
113     (List.filter
114       (fun ((key,_) as p) -> Pcre.pmatch ~pat:"^param\\." key)
115       params)
116
117 let page_RE = Pcre.regexp "&param\\.page=\\d+"
118
119 let query_kind_of_req (req: Http_types.request) =
120   match req#path with
121   | "/match" -> "Match"
122   | "/hint" -> "Hint"
123   | "/locate" -> "Locate"
124   | "/elim" -> "Elim"
125   | _ -> assert false
126
127   (* given a uri with a query part in input try to find in it a string
128    * "&param_name=..." (where param_name is given). If found its value will be
129    * set to param_value. If not, a trailing "&param_name=param_value" (where
130    * both are given) is added to the input string *)
131 let patch_param param_name param_value url =
132   let rex = Pcre.regexp (sprintf "&%s=[^&]*" (Pcre.quote param_name)) in
133   if Pcre.pmatch ~rex url then
134     Pcre.replace ~rex ~templ:(sprintf "%s=%s" param_name param_value) url
135   else
136     sprintf "%s&%s=%s" url param_name param_value
137
138 let send_results results
139   ?(id_to_uris = CicTextualParser2.EnvironmentP3.of_string "") 
140    (req: Http_types.request) outchan
141   =
142   let query_kind = query_kind_of_req req in
143   let interp = try req#param "interp" with Http_types.Param_not_found _ -> "" in
144   let page_link anchor page =
145     try
146       let this = req#param "this" in
147       let target =
148         (patch_param "param.interp" interp
149            (patch_param "param.page" (string_of_int page)
150               this))
151       in
152       let target = Pcre.replace ~pat:"&" ~templ:"&" target in
153       sprintf "<a href=\"%s\">%s</a>" target anchor
154     with Http_types.Param_not_found _ -> ""
155   in
156   Http_daemon.send_basic_headers ~code:(`Code 200) outchan ;
157   Http_daemon.send_header "Content-Type" "text/xml" outchan;
158   Http_daemon.send_CRLF outchan ;
159   let subst =
160     match results with
161     | `Results results ->
162         let page = try int_of_string (req#param "page") with _ -> 1 in
163         let results_no = List.length results in
164         let results_per_page =
165           Helm_registry.get_int "search_engine.results_per_page"
166         in
167         let pages =
168           if results_no mod results_per_page = 0 then
169             results_no / results_per_page
170           else
171             results_no / results_per_page + 1
172         in
173         let pages = if pages = 0 then 1 else pages in
174         let (summary, results) = MooglePp.theory_of_result page results in
175         [ tag "PAGE", string_of_int page;
176           tag "PAGES", string_of_int pages;
177           tag "PREV_LINK", (if page > 1 then page_link "Prev" (page-1) else "");
178           tag "NEXT_LINK",
179             (if page < pages then page_link "Next" (page+1) else "");
180           tag "QUERY_KIND", query_kind;
181           tag "QUERY_SUMMARY", summary;
182           tag "RESULTS", results ]
183     | `Error msg ->
184         [ tag "PAGE", "1";
185           tag "PAGES", "1";
186           tag "PREV_LINK", "";
187           tag "NEXT_LINK", "";
188           tag "QUERY_KIND", query_kind;
189           tag "QUERY_SUMMARY", "error";
190           tag "RESULTS", msg ]
191   in
192   let advanced =
193     try
194       req#param "advanced"
195     with Http_types.Param_not_found _ -> "no"
196   in
197   let subst =
198     (tag "SEARCH_ENGINE_URL", my_own_url) ::
199     (tag "ADVANCED", advanced) ::
200     (tag "EXPRESSION", req#param "expression") ::
201     add_param_substs req#params @
202     (if advanced = "no" then
203       [ tag "SIMPLE_CHECKED", "checked='true'";
204         tag "ADVANCED_CHECKED", "" ]
205     else
206       [ tag "SIMPLE_CHECKED", "";
207         tag "ADVANCED_CHECKED", "checked='true'" ]) @
208     subst
209   in
210   iter_file
211     (fun line ->
212       let new_aliases =
213         CicTextualParser2.EnvironmentP3.to_string id_to_uris
214       in
215       let processed_line =
216         apply_substs
217           (* CSC: Bug here: this is a string, not an array! *)
218           ((tag "NEW_ALIASES", "'" ^ javascript_quote new_aliases ^ "'") ::
219             subst) 
220           line
221       in
222       output_string outchan (processed_line ^ "\n"))
223     moogle_TPL
224
225 let exec_action dbd (req: Http_types.request) outchan =
226   let term_str = req#param "expression" in
227   let (context, metasenv) = ([], []) in
228   let id_to_uris_raw = 
229     try req#param "aliases" 
230     with Http_types.Param_not_found _ -> ""
231   in
232   let parse_interpretation_choices choices =
233     List.map int_of_string (Pcre.split ~pat:" " choices) in
234   let parse_choices choices_raw =
235     let choices = Pcre.split ~pat:";" choices_raw in
236     List.fold_left
237       (fun f x ->
238          match Pcre.split ~pat:"\\s" x with
239            | ""::id::tail
240            | id::tail when id<>"" ->
241                (fun id' ->
242                   if id = id' then
243                     Some (List.map (fun u -> Netencoding.Url.decode u) tail)
244                   else
245                     f id')
246            | _ -> failwith "Can't parse choices")
247       (fun _ -> None)
248       choices
249   in
250   let id_to_uris = CicTextualParser2.EnvironmentP3.of_string id_to_uris_raw in
251   let id_to_choices =
252     try
253       parse_choices (req#param "choices")
254     with Http_types.Param_not_found _ -> (fun _ -> None)
255   in
256   let interpretation_choices =
257     try
258       let choices_raw = req#param "interpretation_choices" in
259       if choices_raw = "" then None 
260       else Some (parse_interpretation_choices choices_raw)
261     with Http_types.Param_not_found _ -> None
262   in 
263   let module Chat: DisambiguateTypes.Callbacks =
264     struct
265       let interactive_user_uri_choice ~selection_mode ?ok
266         ?enable_button_for_non_vars ~(title: string) ~(msg: string)
267         ~(id: string) (choices: string list)
268       =
269         match id_to_choices id with
270         | Some choices -> choices
271         | None -> List.filter nonvar choices
272
273       let interactive_interpretation_choice interpretations =
274         match interpretation_choices with
275         | Some l -> l
276         | None ->
277             let html_interpretations =
278               MooglePp.html_of_interpretations interpretations
279             in
280             Http_daemon.send_basic_headers ~code:(`Code 200) outchan ;
281             Http_daemon.send_CRLF outchan ;
282             let advanced =
283               try
284                 req#param "advanced"
285               with Http_types.Param_not_found _ -> "no"
286             in
287             let query_kind = query_kind_of_req req in
288             iter_file
289               (fun line ->
290                  let processed_line =
291                    apply_substs
292                      [ tag "SEARCH_ENGINE_URL", my_own_url;
293                        tag "ADVANCED", advanced;
294                        tag "INTERPRETATIONS", html_interpretations;
295                        tag "CURRENT_CHOICES", req#param "choices";
296                        tag "EXPRESSION", req#param "expression";
297                        tag "QUERY_KIND", query_kind;
298                        tag "QUERY_SUMMARY", "disambiguation";
299                        tag "ACTION", string_tail req#path ]
300                      line
301                  in
302                  output_string outchan (processed_line ^ "\n"))
303               choices_TPL;
304             raise Chat_unfinished
305
306       let input_or_locate_uri ~title ?id () =
307         match id with
308         | Some id -> raise (Unbound_identifier id)
309         | None -> assert false
310     end
311   in
312   let module Disambiguate' = Disambiguate.Make(Chat) in
313   let ast = CicTextualParser2.parse_term (Stream.of_string term_str) in
314   let (id_to_uris, metasenv, term) =
315     match
316       Disambiguate'.disambiguate_term dbd context metasenv ast id_to_uris
317     with
318     | [id_to_uris,metasenv,term,_] -> id_to_uris,metasenv,term
319     | _ -> assert false
320   in
321   let uris =
322     match req#path with
323     | "/match" -> MetadataQuery.match_term ~dbd term
324     | "/hint" ->
325         let status = ProofEngineTypes.initial_status term metasenv in
326         let intros = PrimitiveTactics.intros_tac () in
327         let subgoals = ProofEngineTypes.apply_tactic intros status in
328         (match subgoals with
329         | proof, [goal] ->
330             let (uri,metasenv,bo,ty) = proof in
331             List.map fst (MetadataQuery.hint ~dbd (proof, goal))
332         | _ -> assert false)
333     | "/elim" ->
334         let uri =
335           match term with
336           | Cic.MutInd (uri, typeno, _) ->
337               UriManager.string_of_uriref (uri, [typeno])
338           | _ -> assert false
339         in
340         MetadataQuery.elim ~dbd uri
341     | _ -> assert false
342   in
343   send_results ~id_to_uris (`Results uris) req outchan
344
345 let callback dbd (req: Http_types.request) outchan =
346   try
347     debug_print (sprintf "Received request: %s" req#path);
348     (match req#path with
349     | "/getpage" ->
350           (* TODO implement "is_permitted" *)
351         (let is_permitted _ = true in
352         let page = req#param "url" in
353         let preprocess =
354           (try
355             bool_of_string (req#param "preprocess")
356           with Invalid_argument _ | Http_types.Param_not_found _ -> false)
357         in
358         (match page with
359         | page when is_permitted page ->
360             (let fname = sprintf "%s/%s" pages_dir page in
361             Http_daemon.send_basic_headers ~code:(`Code 200) outchan;
362             Http_daemon.send_header "Content-Type" "text/html" outchan;
363             Http_daemon.send_CRLF outchan;
364             if preprocess then begin
365               iter_file
366                 (fun line ->
367                   output_string outchan
368                     ((apply_substs
369                        ((tag "SEARCH_ENGINE_URL", my_own_url) ::
370                         (tag "ADVANCED", "no") ::
371                         (tag "RESULTS", "") ::
372                         add_param_substs req#params)
373                        line) ^
374                     "\n"))
375                 fname
376             end else
377               Http_daemon.send_file ~src:(Http_types.FileSrc fname) outchan)
378         | page -> Http_daemon.respond_forbidden ~url:page outchan))
379     | "/help" -> Http_daemon.respond ~body:daemon_name outchan
380     | "/locate" ->
381         let initial_expression =
382           try req#param "expression" with Http_types.Param_not_found _ -> ""
383         in
384         let expression =
385           Pcre.replace ~pat:"\\s*$"
386             (Pcre.replace ~pat:"^\\s*" initial_expression)
387         in
388         if expression = "" then
389           send_results (`Results []) req outchan
390         else begin
391           let results = MetadataQuery.locate ~dbd expression in
392           send_results (`Results results) req outchan
393         end
394     | "/hint"
395     | "/elim"
396     | "/match" -> exec_action dbd req outchan
397     | invalid_request ->
398         Http_daemon.respond_error ~code:(`Status (`Client_error `Bad_request))
399           outchan);
400     debug_print (sprintf "%s done!" req#path)
401   with
402   | Chat_unfinished -> ()
403   | Http_types.Param_not_found attr_name ->
404       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
405   | CicTextualParser2.Parse_error (_, msg) ->
406       send_results (`Error (MooglePp.pp_error "Parse_error" msg)) req outchan
407   | Unbound_identifier id ->
408       send_results (`Error (MooglePp.pp_error "Unbound identifier" id)) req
409         outchan
410   | exn ->
411       let exn_string = Printexc.to_string exn in
412       debug_print exn_string;
413       let msg = MooglePp.pp_error "Uncaught exception" exn_string in
414       send_results (`Error msg) req outchan
415
416 let _ =
417   printf "%s started and listening on port %d\n" daemon_name port;
418   printf "Current directory is %s\n" (Sys.getcwd ());
419   printf "HTML directory is %s\n" pages_dir;
420   flush stdout;
421   Unix.putenv "http_proxy" "";
422   let dbd =
423     Mysql.quick_connect
424       ~host:(Helm_registry.get "db.host")
425       ~database:(Helm_registry.get "db.database")
426       ~user:(Helm_registry.get "db.user")
427       ()
428   in
429   Http_daemon.start' ~port (callback dbd);
430   printf "%s is terminating, bye!\n" daemon_name
431