]> matita.cs.unibo.it Git - helm.git/blob - helm/searchEngine/searchEngine.ml
7b5635704f782e4b19cdfb4db942fafc3777b3f0
[helm.git] / helm / searchEngine / searchEngine.ml
1
2 (* Copyright (C) 2002, HELM Team.
3  * 
4  * This file is part of HELM, an Hypertextual, Electronic
5  * Library of Mathematics, developed at the Computer Science
6  * Department, University of Bologna, Italy.
7  * 
8  * HELM is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  * 
13  * HELM is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with HELM; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21  * MA  02111-1307, USA.
22  * 
23  * For details, see the HELM World-Wide-Web page,
24  * http://cs.unibo.it/helm/.
25  *)
26
27 let debug = true;;
28 let debug_print s = if debug then prerr_endline s;;
29 Http_common.debug := true;;
30
31 open Printf;;
32
33 let daemon_name = "Search Engine";;
34 let default_port = 58085;;
35 let port_env_var = "SEARCH_ENGINE_PORT";;
36
37 let pages_dir = "html";; (* relative to searchEngine's document root *)
38 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
39 let interactive_interpretation_choice_TPL = pages_dir ^ "/templateambigpdq2.html";;
40 let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";;
41
42 exception Chat_unfinished
43
44   (** chain application of Pcre substitutions *)
45 let rec apply_substs substs line =
46   match substs with
47   | [] -> line
48   | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
49   (** fold like function on files *)
50 let fold_file f init fname =
51   let inchan = open_in fname in
52   let rec fold_lines' value =
53     try 
54       let line = input_line inchan in 
55       fold_lines' (f value line)
56     with End_of_file -> value
57   in
58   let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
59   close_in inchan;
60   res
61   (** iter like function on files *)
62 let iter_file f = fold_file (fun _ line -> f line) ()
63
64 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
65     interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE) =
66   (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
67   Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
68   Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
69   Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@")
70
71 let port =
72   try
73     int_of_string (Sys.getenv port_env_var)
74   with
75   | Not_found -> default_port
76   | Failure "int_of_string" ->
77       prerr_endline "Warning: invalid port, reverting to default";
78       default_port
79 in
80 let pp_result result =
81   let result_string = MQueryUtil.text_of_result result "\n" in
82   (sprintf "<html>\n<head>\n</head>\n<body>\n<pre>%s</pre>\n</body>\n</html>"
83     result_string)
84 in
85 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>" in
86 let bad_request body outchan =
87   Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
88 in
89 let contype = "Content-Type", "text/html" in
90
91 (* SEARCH ENGINE functions *)
92
93 let refine_constraints (x, y, z) = (x, y, z), (Some x, Some y, Some z) in
94
95 (* HTTP DAEMON CALLBACK *)
96
97 let callback (req: Http_types.request) outchan =
98   try
99     debug_print (sprintf "Received request: %s" req#path);
100     (match req#path with
101     | "/execute" ->
102         let query_string = req#param "query" in
103         let lexbuf = Lexing.from_string query_string in
104         let query = MQueryUtil.query_of_text lexbuf in
105         let result = MQueryGenerator.execute_query query in
106         let result_string = MQueryUtil.text_of_result result "\n" in
107         Http_daemon.respond
108           ~body:
109             (sprintf "<html><body><pre>%s</pre></body></html>" result_string)
110           ~headers:[contype] outchan
111     | "/locate" ->
112         let id = req#param "id" in
113         let result = MQueryGenerator.locate id in
114         Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
115     | "/getpage" ->
116         (let is_permitted _ = true in
117         let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
118         match req#param "url" with
119         | page when is_permitted (remove_fragment page) ->
120             Http_daemon.respond_file
121               ~fname:(sprintf "%s/%s" pages_dir (remove_fragment page)) outchan
122         | page -> Http_daemon.respond_forbidden ~url:page outchan)
123     | "/searchPattern" ->
124         let term_string = req#param "term" in
125         let lexbuf = Lexing.from_string term_string in
126         let (context, metasenv) = ([], []) in
127         let (dom, mk_metasenv_and_expr) =
128           CicTextualParserContext.main
129             ~context ~metasenv CicTextualLexer.token lexbuf
130         in
131         let id_to_uris_raw = req#param "aliases" in
132         let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
133         let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
134           | [] -> keys, lookup
135           | "alias" :: key :: value :: rest ->
136               parse_tokens
137                 (key::keys)
138                 (fun id ->
139                   if id = key then
140                     Some (Disambiguate.cic_textual_parser_uri_of_string value)
141                   else lookup id)
142                 rest
143           | _ -> failwith "Can't parse aliases"
144         in
145         let parse_choices choices_raw =
146           let choices = Pcre.split ~pat:";" choices_raw in
147           List.fold_left
148             (fun f x ->
149               match Pcre.split ~pat:"\\s" x with
150               | ""::id::tail
151               | id::tail when id<>"" ->
152                   (fun id' ->
153                     if id = id' then
154                       Some (List.map (fun u -> Netencoding.Url.decode u) tail)
155                     else
156                       f id')
157               | _ -> failwith "Can't parse choices")
158             (fun _ -> None)
159             choices
160         in
161         let id_to_uris = parse_tokens [] (fun _ -> None) tokens in
162         let id_to_choices =
163           try
164             let choices_raw = req#param "choices" in
165             parse_choices choices_raw
166           with Http_types.Param_not_found _ -> (fun _ -> None)
167         in
168         let module Chat: Disambiguate.Callbacks =
169           struct
170
171             let output_html = prerr_endline
172
173             let interactive_user_uri_choice
174               ~selection_mode ?ok
175               ?enable_button_for_non_vars ~(title: string) ~(msg: string)
176               ~(id: string) (choices: string list)
177               =
178                 (match id_to_choices id with
179                 | Some choices -> choices
180                 | None ->
181                   let msg = Pcre.replace ~pat:"\"" ~templ:"\\\"" msg in
182                   (match selection_mode with
183                   | `SINGLE -> assert false
184                   | `EXTENDED ->
185                       iter_file
186                         (fun line ->
187                           let formatted_choices =
188                             String.concat ","
189                               (List.map (fun uri -> sprintf "\"%s\"" uri) choices)
190                           in
191                           let processed_line =
192                             apply_substs
193                               [title_tag_RE, title;
194                                choices_tag_RE, formatted_choices;
195                                msg_tag_RE, msg;
196                                id_to_uris_RE, id_to_uris_raw;
197                                id_RE, id]
198                               line
199                           in
200                           output_string outchan processed_line)
201                         interactive_user_uri_choice_TPL;
202                       raise Chat_unfinished))
203
204             let interactive_interpretation_choice interpretations =
205               let html_interpretations_labels =
206                 String.concat ", "
207                   (List.map
208                     (fun l ->
209                       "\"" ^
210                       (String.concat "<br />"
211                         (List.map
212                           (fun (id, value) ->
213                             (sprintf "alias %s %s" id value))
214                           l)) ^
215                       "\"")
216                   interpretations)
217               in
218               let html_interpretations =
219                 String.concat ", "
220                   (List.map
221                     (fun l ->
222                       "\"" ^
223                       (String.concat " "
224                         (List.map
225                           (fun (id, value) ->
226                             (sprintf "alias %s %s"
227                               id
228                               (Disambiguate.wrong_xpointer_format_from_wrong_xpointer_format'
229                                 value)))
230                           l)) ^
231                       "\"")
232                     interpretations)
233               in
234               iter_file
235                 (fun line ->
236                   let processed_line =
237                     apply_substs
238                       [interpretations_RE, html_interpretations;
239                        interpretations_labels_RE, html_interpretations_labels]
240                       line
241                   in
242                   output_string outchan processed_line)
243                 interactive_interpretation_choice_TPL;
244               raise Chat_unfinished
245
246             let input_or_locate_uri ~title =
247               UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
248
249           end
250         in
251         let module Disambiguate' = Disambiguate.Make (Chat) in
252         let (id_to_uris', metasenv', term') =
253           Disambiguate'.disambiguate_input
254             context metasenv dom mk_metasenv_and_expr id_to_uris
255         in
256         (match metasenv' with
257         | [] ->
258             let must = MQueryLevels2.get_constraints term' in
259             let must',only = refine_constraints must in
260             let results = MQueryGenerator.searchPattern must' only in 
261             debug_print "FASE 3";
262             iter_file
263               (fun line ->
264                 let new_aliases =
265                   match id_to_uris' with
266                   | (domain, f) ->
267                       String.concat ", "
268                         (List.map
269                           (fun name ->
270                             sprintf "\"alias %s cic:%s\""
271                               name
272                               (match f name with
273                               | None -> assert false
274                               | Some t ->
275                                   Disambiguate.string_of_cic_textual_parser_uri
276                                     t))
277                           domain)
278                 in
279                 let processed_line =
280                   apply_substs
281                     [results_RE, MQueryUtil.text_of_result results "\n";
282                      new_aliases_RE, new_aliases]
283                     line
284                 in
285                 output_string outchan processed_line)
286               final_results_TPL
287         | _ -> (* unable to instantiate some implicit variable *)
288             Http_daemon.respond
289               ~headers:[contype]
290               ~body:"some implicit variables are still unistantiated :-("
291               outchan)
292
293     | invalid_request ->
294         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
295     debug_print (sprintf "%s done!" req#path)
296   with
297   | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
298   | Http_types.Param_not_found attr_name ->
299       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
300   | exc ->
301       Http_daemon.respond
302         ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
303         outchan
304 in
305 printf "%s started and listening on port %d\n" daemon_name port;
306 printf "current directory is %s\n" (Sys.getcwd ());
307 flush stdout;
308 Unix.putenv "http_proxy" "";
309 Mqint.set_database Mqint.postgres_db;
310 Mqint.init "host=mowgli.cs.unibo.it dbname=helm_mowgli_new_schema user=helm";
311 Http_daemon.start' ~port callback;
312 Mqint.close ();
313 printf "%s is terminating, bye!\n" daemon_name
314