]> matita.cs.unibo.it Git - helm.git/blob - helm/searchEngine/searchEngine.ml
fc0fb9cbee4ec2af67bb77d7f2b12ccfc1f269c2
[helm.git] / helm / searchEngine / searchEngine.ml
1 (* Copyright (C) 2002, 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 module T = MQGTypes
27 module U = MQGUtil
28 module G = MQueryGenerator
29 module C = MQIConn
30
31 open Http_types ;;
32
33 let debug = true;;
34 let debug_print s = if debug then prerr_endline s;;
35 Http_common.debug := true;;
36 (* Http_common.debug := true;; *)
37
38 open Printf;;
39
40 let daemon_name = "Search Engine";;
41
42   (* First of all we load the configuration *)
43 let _ =
44  let configuration_file = "/projects/helm/etc/searchEngine.conf.xml" in
45   Helm_registry.load_from configuration_file
46 ;;
47
48 let pages_dir = Helm_registry.get "search_engine.html_dir";;
49
50   (** accepted HTTP servers for ask_uwobo method forwarding *)
51 let valid_servers= Helm_registry.get_string_list "search_engine.valid_servers";;
52
53
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";;
59
60 exception Chat_unfinished
61
62 let javascript_quote s =
63  let rex = Pcre.regexp "'" in
64  let rex' = Pcre.regexp "\"" in
65   Pcre.replace ~rex ~templ:"\\'"
66    (Pcre.replace ~rex:rex' ~templ:"\\\"" s)
67 ;;
68
69   (* build a bool from a 1-character-string *)
70 let bool_of_string' = function
71   | "0" -> false
72   | "1" -> true
73   | s -> failwith ("Can't parse a boolean from string: " ^ s)
74 ;;
75
76   (* build an int option from a string *)
77 let int_of_string' = function
78   | "_" -> None
79   | s ->
80       try
81         Some (int_of_string s)
82       with Failure "int_of_string" ->
83         failwith ("Can't parse an int option from string: " ^ s)
84 ;;
85
86   (* HTML pretty printers for mquery_generator types *)
87
88 let html_of_r_obj (pos, uri) =
89   sprintf
90     "<tr><td><input type='checkbox' name='constr_obj' checked='on'/></td><td>%s</td><td>%s</td><td>%s</td></tr>"
91     uri (U.text_of_position pos)
92     (if U.is_main_position pos then
93       sprintf "<input name='obj_depth' size='2' type='text' value='%s' />"
94         (U.text_of_depth pos "")
95     else
96       "<input type=\"hidden\" name=\"obj_depth\" />")
97 ;;
98
99 let html_of_r_rel pos =
100   sprintf
101     "<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>"
102     (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
103 ;;
104
105 let html_of_r_sort (pos, sort) =
106   sprintf
107     "<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>"
108     (U.text_of_sort sort) (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
109 ;;
110
111   (** pretty print a MathQL query result to an HELM theory file *)
112 let theory_of_result result =
113  let results_no = List.length result in
114   if results_no > 0 then
115    let mode = if results_no > 10 then "linkonly" else "typeonly" in
116    let results =
117     let idx = ref (results_no + 1) in
118      List.fold_right
119       (fun (uri,attrs) i ->
120         decr idx ;
121         "<tr><td valign=\"top\">" ^ string_of_int !idx ^ ".</td><td><ht:OBJECT uri=\"" ^ uri ^ "\" mode=\"" ^ mode ^ "\"/></td></tr>" ^  i
122       ) result ""
123    in
124     "<h1>Query Results:</h1><table xmlns:ht=\"http://www.cs.unibo.it/helm/namespaces/helm-theory\">" ^ results ^ "</table>"
125   else
126     "<h1>Query Results:</h1><p>No results found!</p>"
127 ;;
128
129 let pp_result result =
130  "<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>"
131 ;;
132
133   (** chain application of Pcre substitutions *)
134 let rec apply_substs substs line =
135   match substs with
136   | [] -> line
137   | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
138   (** fold like function on files *)
139 let fold_file f init fname =
140   let inchan = open_in fname in
141   let rec fold_lines' value =
142     try 
143       let line = input_line inchan in 
144       fold_lines' (f value line)
145     with End_of_file -> value
146   in
147   let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
148   close_in inchan;
149   res
150   (** iter like function on files *)
151 let iter_file f = fold_file (fun _ line -> f line) ()
152
153 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
154     interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE,
155     form_RE, variables_initialization_RE)
156   =
157   (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
158   Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
159   Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
160   Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@", Pcre.regexp "@FORM@",
161   Pcre.regexp "@VARIABLES_INITIALIZATION@")
162 let server_and_port_url_RE = Pcre.regexp "^http://([^/]+)/.*$"
163
164 let port = Helm_registry.get_int "search_engine.port";;
165
166 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>";;
167
168 let bad_request body outchan =
169   Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
170 ;;
171
172 let contype = "Content-Type", "text/html";;
173
174 (* SEARCH ENGINE functions *)
175
176 let get_constraints term =
177  function
178     | "/locateInductivePrinciple" ->
179       None,
180       (CGLocateInductive.get_constraints term),
181       (None,None,None)
182     | "/searchPattern" ->
183      let constr_obj, constr_rel, constr_sort =
184        CGSearchPattern.get_constraints term in
185      (Some CGSearchPattern.universe),
186      (constr_obj, constr_rel, constr_sort),
187      (Some constr_obj, Some constr_rel, Some constr_sort)
188     | "/matchConclusion" ->
189      let list_of_must, only = CGMatchConclusion.get_constraints [] [] term in
190 (* FG: there is no way to choose the block number ***************************)
191      let block = pred (List.length list_of_must) in 
192       (Some CGMatchConclusion.universe), 
193       (List.nth list_of_must block, [], []), (Some only, None, None)
194     | _ -> assert false
195 ;;
196
197 (*
198   format:
199     <must_obj> ':' <must_rel> ':' <must_sort> ':' <only_obj> ':' <only_rel> ':' <only_sort>
200
201     <must_*> ::= ('0'|'1') ('_'|<int>) (',' ('0'|'1') ('_'|<int>))*
202     <only> ::= '0'|'1'
203 *)
204 let add_user_constraints ~constraints
205  ((obj, rel, sort), (only_obj, only_rel, only_sort))
206 =
207   let parse_must s =
208     let l = Pcre.split ~pat:"," s in
209     (try
210       List.map
211         (fun s ->
212           let subs = Pcre.extract ~pat:"^(.)(\\d+|_)$" s in
213           (bool_of_string' subs.(1), int_of_string' subs.(2)))
214         l
215      with
216       Not_found -> failwith ("Can't parse constraint string: " ^ constraints)
217     )
218   in
219     (* to be used on "obj" *)
220   let add_user_must33 user_must must =
221     List.map2
222      (fun (b, i) (p, u) ->
223        if b then Some (U.set_full_position p i, u) else None)
224      user_must must
225   in
226     (* to be used on "rel" *)
227   let add_user_must22 user_must must =
228     List.map2
229      (fun (b, i) p -> if b then Some (U.set_main_position p i) else None)
230      user_must must
231   in
232     (* to be used on "sort" *)
233   let add_user_must32 user_must must =
234     List.map2
235      (fun (b, i) (p, s)-> if b then Some (U.set_main_position p i, s) else None)
236      user_must must
237   in
238   match Pcre.split ~pat:":" constraints with
239   | [user_obj;user_rel;user_sort;user_only_obj;user_only_rel;user_only_sort] ->
240       let
241        (user_obj,user_rel,user_sort,user_only_obj,user_only_rel,user_only_sort)
242       =
243         (parse_must user_obj,
244         parse_must user_rel,
245         parse_must user_sort,
246         bool_of_string' user_only_obj,
247         bool_of_string' user_only_rel,
248         bool_of_string' user_only_sort)
249       in
250       let only' =
251        (if user_only_obj  then only_obj else None),
252        (if user_only_rel  then only_rel else None),
253        (if user_only_sort then only_sort else None)
254       in
255       let must' =
256        let rec filter_some =
257         function
258            [] -> []
259          | None::tl -> filter_some tl
260          | (Some x)::tl -> x::(filter_some tl) 
261        in
262         filter_some (add_user_must33 user_obj obj),
263         filter_some (add_user_must22 user_rel rel),
264         filter_some (add_user_must32 user_sort sort)
265       in
266       (must', only')
267   | _ -> failwith ("Can't parse constraint string: " ^ constraints)
268 in
269
270 (* HTTP DAEMON CALLBACK *)
271
272 let callback mqi_handle (req: Http_types.request) outchan =
273   try
274     debug_print (sprintf "Received request: %s" req#path);
275     (match req#path with
276     | "/help" -> Http_daemon.respond ~body:"HELM Search Engine" outchan
277     | "/execute" ->
278         let query_string = req#param "query" in
279         let lexbuf = Lexing.from_string query_string in
280         let query = MQueryUtil.query_of_text lexbuf in
281         let result = MQueryInterpreter.execute mqi_handle query in
282         let result_string = pp_result result in
283         Http_daemon.respond ~body:result_string ~headers:[contype] outchan
284     | "/locate" ->
285         let id = req#param "id" in
286         let query = G.locate id in
287         let result = MQueryInterpreter.execute mqi_handle query in
288         Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
289     | "/unreferred" ->
290         let target = req#param "target" in
291         let source = req#param "source" in
292         let query = G.unreferred target source in
293         let result = MQueryInterpreter.execute mqi_handle query in
294         Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
295     | "/getpage" ->
296         (* TODO implement "is_permitted" *)
297         (let is_permitted _ = true in
298         let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
299         let page = remove_fragment (req#param "url") in
300         let preprocess =
301           (try
302             bool_of_string (req#param "preprocess")
303           with Invalid_argument _ | Http_types.Param_not_found _ -> false)
304         in
305         (match page with
306         | page when is_permitted page ->
307             (let fname = sprintf "%s/%s" pages_dir (remove_fragment page) in
308             Http_daemon.send_basic_headers ~code:200 outchan;
309             Http_daemon.send_header "Content-Type" "text/html" outchan;
310             Http_daemon.send_CRLF outchan;
311             if preprocess then begin
312               iter_file
313                 (fun line ->
314                   output_string outchan
315                     ((apply_substs
316                        (List.map
317                          (function (key,value) ->
318                            let key' =
319                             (Pcre.extract ~pat:"param\\.(.*)" key).(1)
320                            in
321                             Pcre.regexp ("@" ^ key' ^ "@"), value
322                          )
323                          (List.filter
324                            (fun (key,_) as p-> Pcre.pmatch ~pat:"^param\\." key)
325                            req#params)
326                        )
327                        line) ^
328                     "\n"))
329                 fname
330             end else
331               Http_daemon.send_file ~src:(FileSrc fname) outchan)
332         | page -> Http_daemon.respond_forbidden ~url:page outchan))
333     | "/ask_uwobo" ->
334       let url = req#param "url" in
335       let server_and_port =
336         (Pcre.extract ~rex:server_and_port_url_RE url).(1)
337       in
338       if List.mem server_and_port valid_servers then
339         Http_daemon.respond
340           ~headers:["Content-Type", "text/html"]
341           ~body:(Http_client.http_get url)
342           outchan
343       else
344         Http_daemon.respond
345           ~body:(pp_error ("Untrusted UWOBO server: " ^ server_and_port))
346           outchan
347     | "/searchPattern"
348     | "/matchConclusion"
349     | "/locateInductivePrinciple" ->
350         let term_string = req#param "term" in
351         let (context, metasenv) = ([], []) in
352         let id_to_uris_raw = req#param "aliases" in
353         let parse_interpretation_choices choices =
354          List.map int_of_string (Pcre.split ~pat:" " choices) in
355         let parse_choices choices_raw =
356           let choices = Pcre.split ~pat:";" choices_raw in
357           List.fold_left
358             (fun f x ->
359               match Pcre.split ~pat:"\\s" x with
360               | ""::id::tail
361               | id::tail when id<>"" ->
362                   (fun id' ->
363                     if id = id' then
364                       Some (List.map (fun u -> Netencoding.Url.decode u) tail)
365                     else
366                       f id')
367               | _ -> failwith "Can't parse choices")
368             (fun _ -> None)
369             choices
370         in
371         let id_to_uris =
372          DisambiguatingParser.EnvironmentP3.of_string id_to_uris_raw in
373         let id_to_choices =
374           try
375             let choices_raw = req#param "choices" in
376             parse_choices choices_raw
377           with Http_types.Param_not_found _ -> (fun _ -> None)
378         in
379         let interpretation_choices =
380           try
381             let choices_raw = req#param "interpretation_choices" in
382             Some (parse_interpretation_choices choices_raw)
383           with Http_types.Param_not_found _ -> None
384         in
385         let module Chat: DisambiguateTypes.Callbacks =
386           struct
387
388             let interactive_user_uri_choice
389               ~selection_mode ?ok
390               ?enable_button_for_non_vars ~(title: string) ~(msg: string)
391               ~(id: string) (choices: string list)
392               =
393                 (match id_to_choices id with
394                 | Some choices -> choices
395                 | None ->
396                   let msg = Pcre.replace ~pat:"\'" ~templ:"\\\'" msg in
397                   (match selection_mode with
398                   | `SINGLE -> assert false
399                   | `MULTIPLE ->
400                       Http_daemon.send_basic_headers ~code:200 outchan ;
401                       Http_daemon.send_CRLF outchan ;
402                       iter_file
403                         (fun line ->
404                           let formatted_choices =
405                             String.concat ","
406                               (List.map (fun uri -> sprintf "\'%s\'" uri) choices)
407                           in
408                           let processed_line =
409                             apply_substs
410                               [title_tag_RE, title;
411                                choices_tag_RE, formatted_choices;
412                                msg_tag_RE, msg;
413                                id_to_uris_RE, id_to_uris_raw;
414                                id_RE, id]
415                               line
416                           in
417                           output_string outchan (processed_line ^ "\n"))
418                         interactive_user_uri_choice_TPL;
419                       raise Chat_unfinished))
420
421             let interactive_interpretation_choice interpretations =
422              match interpretation_choices with
423                 Some l -> prerr_endline "CARRAMBA" ; l
424               | None ->
425                 let html_interpretations_labels =
426                   String.concat ", "
427                     (List.map
428                       (fun l ->
429                         "\'" ^
430                         (String.concat "<br />"
431                           (List.map
432                             (fun (id, value) ->
433                               let id = javascript_quote id in
434                               let value = javascript_quote value in
435                                sprintf "%s = %s" id value)
436                             l)) ^
437                         "\'")
438                     interpretations)
439                 in
440                 let html_interpretations =
441                  let rec aux n =
442                   function
443                      [] -> []
444                    | _::tl -> ("'" ^ string_of_int n ^ "'")::(aux (n+1) tl)
445                  in
446                   String.concat ", " (aux 0 interpretations)
447                 in
448                 Http_daemon.send_basic_headers ~code:200 outchan ;
449                 Http_daemon.send_CRLF outchan ;
450                 iter_file
451                   (fun line ->
452                     let processed_line =
453                       apply_substs
454                         [interpretations_RE, html_interpretations;
455                          interpretations_labels_RE, html_interpretations_labels]
456                         line
457                     in
458                     output_string outchan (processed_line ^ "\n"))
459                   interactive_interpretation_choice_TPL;
460                 raise Chat_unfinished
461
462             let input_or_locate_uri ~title ?id () =
463              assert false
464
465           end
466         in
467         let module Disambiguate' = DisambiguatingParser.Make(Chat) in
468         let (id_to_uris', metasenv', term') =
469          match
470           Disambiguate'.disambiguate_term mqi_handle
471             context metasenv term_string id_to_uris
472          with
473             [id_to_uris',metasenv',term'] -> id_to_uris',metasenv',term'
474           | _ -> assert false
475         in
476           let universe,
477               ((must_obj, must_rel, must_sort) as must'),
478               ((only_obj, only_rel, only_sort) as only) =
479             get_constraints term' req#path
480           in
481           let must'', only' =
482             (try
483               add_user_constraints
484                 ~constraints:(req#param "constraints")
485                 (must', only)
486             with Http_types.Param_not_found _ ->
487               let variables =
488                "var aliases = '" ^ id_to_uris_raw ^ "';\n" ^
489                "var constr_obj_len = " ^
490                 string_of_int (List.length must_obj) ^ ";\n" ^
491                "var constr_rel_len = " ^
492                 string_of_int (List.length must_rel) ^ ";\n" ^
493                "var constr_sort_len = " ^
494                 string_of_int (List.length must_sort) ^ ";\n" in
495               let form =
496                 (if must_obj = [] then "" else
497                   "<h4>Obj constraints</h4>" ^
498                   "<table>" ^
499                   (String.concat "\n" (List.map html_of_r_obj must_obj)) ^
500                   "</table>" ^
501                   (* The following three lines to make Javascript create *)
502                   (* the constr_obj[] and obj_depth[] arrays even if we  *)
503                   (* have only one real entry.                           *)
504                   "<input type=\"hidden\" name=\"constr_obj\" />" ^
505                   "<input type=\"hidden\" name=\"obj_depth\" />") ^
506                 (if must_rel = [] then "" else
507                  "<h4>Rel constraints</h4>" ^
508                  "<table>" ^
509                  (String.concat "\n" (List.map html_of_r_rel must_rel)) ^
510                  "</table>" ^
511                   (* The following two lines to make Javascript create *)
512                   (* the constr_rel[] and rel_depth[] arrays even if   *)
513                   (* we have only one real entry.                      *)
514                   "<input type=\"hidden\" name=\"constr_rel\" />" ^
515                   "<input type=\"hidden\" name=\"rel_depth\" />") ^
516                 (if must_sort = [] then "" else
517                   "<h4>Sort constraints</h4>" ^
518                   "<table>" ^
519                   (String.concat "\n" (List.map html_of_r_sort must_sort)) ^
520                   "</table>" ^
521                   (* The following two lines to make Javascript create *)
522                   (* the constr_sort[] and sort_depth[] arrays even if *)
523                   (* we have only one real entry.                      *)
524                   "<input type=\"hidden\" name=\"constr_sort\" />" ^
525                   "<input type=\"hidden\" name=\"sort_depth\" />") ^
526                   "<h4>Only constraints</h4>" ^
527                   "Enforce Only constraints for objects: " ^
528                     "<input type='checkbox' name='only_obj'" ^
529                     (if only_obj = None then "" else " checked='yes'") ^ " /><br />" ^
530                   "Enforce Rel constraints for objects: " ^
531                     "<input type='checkbox' name='only_rel'" ^
532                     (if only_rel = None then "" else " checked='yes'") ^ " /><br />" ^
533                   "Enforce Sort constraints for objects: " ^
534                     "<input type='checkbox' name='only_sort'" ^
535                     (if only_sort = None then "" else " checked='yes'") ^ " /><br />"
536               in
537               Http_daemon.send_basic_headers ~code:200 outchan ;
538               Http_daemon.send_CRLF outchan ;
539               iter_file
540                 (fun line ->
541                   let processed_line =
542                     apply_substs
543                      [form_RE, form ;
544                       variables_initialization_RE, variables] line
545                   in
546                   output_string outchan (processed_line ^ "\n"))
547                 constraints_choice_TPL;
548                 raise Chat_unfinished)
549           in
550           let query =
551            G.query_of_constraints universe must'' only'
552           in
553           let results = MQueryInterpreter.execute mqi_handle query in 
554            Http_daemon.send_basic_headers ~code:200 outchan ;
555            Http_daemon.send_CRLF outchan ;
556            iter_file
557              (fun line ->
558                let new_aliases =
559                 DisambiguatingParser.EnvironmentP3.to_string id_to_uris' in
560                let processed_line =
561                  apply_substs
562                    [results_RE, theory_of_result results ;
563                     (* CSC: Bug here: this is a string, not an array! *)
564                     new_aliases_RE, "'" ^ javascript_quote new_aliases ^ "'"]
565                    line
566                in
567                output_string outchan (processed_line ^ "\n"))
568              final_results_TPL
569     | invalid_request ->
570         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
571     debug_print (sprintf "%s done!" req#path)
572   with
573   | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
574   | Http_types.Param_not_found attr_name ->
575       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
576   | exc ->
577       let msg = sprintf "Uncaught exception: %s" (Printexc.to_string exc) in
578        debug_print msg ;
579        Http_daemon.respond ~body:(pp_error msg) outchan
580 in
581 printf "%s started and listening on port %d\n" daemon_name port;
582 printf "Current directory is %s\n" (Sys.getcwd ());
583 printf "HTML directory is %s\n" pages_dir;
584 flush stdout;
585 Unix.putenv "http_proxy" "";
586 let mqi_handle = C.init ~log:debug_print () in
587 Http_daemon.start' ~port (callback mqi_handle);
588 C.close mqi_handle;
589 printf "%s is terminating, bye!\n" daemon_name