]> matita.cs.unibo.it Git - helm.git/blob - helm/searchEngine/searchEngine.ml
CVS repository fix: reversion of some lines (related to libhttp) to a working
[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 let debug = true;;
27 let debug_print s = if debug then prerr_endline s;;
28 (* Http_common.debug := true;; *)
29
30 open Printf;;
31
32 let postgresConnectionString =
33  try
34   Sys.getenv "POSTGRESQL_CONNECTION_STRING"
35  with
36   Not_found -> "host=mowgli.cs.unibo.it dbname=helm_mowgli_new_schema user=helm"
37 ;;
38
39 let daemon_name = "Search Engine";;
40 let default_port = 58085;;
41 let port_env_var = "SEARCH_ENGINE_PORT";;
42
43 let pages_dir =
44   try
45     Sys.getenv "SEARCH_ENGINE_HTML_DIR"
46   with Not_found -> "html"  (* relative to searchEngine's document root *)
47 ;;
48 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
49 let interactive_interpretation_choice_TPL = pages_dir ^ "/templateambigpdq2.html";;
50 let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";;
51
52 exception Chat_unfinished
53
54   (** pretty print a MathQL query result to a string *)
55 let text_of_result result sep =
56  let res_string = ref "" in
57   let app = function s -> res_string := !res_string ^ s in
58    MQueryUtil.text_of_result app result sep ;
59    !res_string
60 ;;
61
62   (** chain application of Pcre substitutions *)
63 let rec apply_substs substs line =
64   match substs with
65   | [] -> line
66   | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
67   (** fold like function on files *)
68 let fold_file f init fname =
69   let inchan = open_in fname in
70   let rec fold_lines' value =
71     try 
72       let line = input_line inchan in 
73       fold_lines' (f value line)
74     with End_of_file -> value
75   in
76   let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
77   close_in inchan;
78   res
79   (** iter like function on files *)
80 let iter_file f = fold_file (fun _ line -> f line) ()
81
82 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
83     interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE) =
84   (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
85   Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
86   Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
87   Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@")
88
89 let port =
90   try
91     int_of_string (Sys.getenv port_env_var)
92   with
93   | Not_found -> default_port
94   | Failure "int_of_string" ->
95       prerr_endline "Warning: invalid port, reverting to default";
96       default_port
97 in
98 let pp_result result =
99  let res_string = text_of_result result "\n" in
100   (sprintf "<html>\n<head>\n</head>\n<body>\n<pre>%s</pre>\n</body>\n</html>"
101     res_string)
102 in
103 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>" in
104 let bad_request body outchan =
105   Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
106 in
107 let contype = "Content-Type", "text/html" in
108
109 (* SEARCH ENGINE functions *)
110
111 let refine_constraints (x, y, z) = (x, y, z), (Some x, Some y, Some z) in
112
113 (* HTTP DAEMON CALLBACK *)
114
115 let callback (req: Http_types.request) outchan =
116   try
117     debug_print (sprintf "Received request: %s" req#path);
118     if req#path <> "/getpage" then
119       Mqint.init postgresConnectionString;
120     (match req#path with
121     | "/execute" ->
122         let query_string = req#param "query" in
123         let lexbuf = Lexing.from_string query_string in
124         let query = MQueryUtil.query_of_text lexbuf in
125         let result = MQueryGenerator.execute_query query in
126         let result_string = text_of_result result "\n" in
127         Http_daemon.respond
128           ~body:
129             (sprintf "<html><body><pre>%s</pre></body></html>" result_string)
130           ~headers:[contype] outchan
131     | "/locate" ->
132         let id = req#param "id" in
133         let result = MQueryGenerator.locate id in
134         Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
135     | "/getpage" ->
136         (* TODO implement "is_permitted" *)
137         (let is_permitted _ = true in
138         let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
139         let page = remove_fragment (req#param "url") in
140         match page with
141         | page when is_permitted page ->
142             Http_daemon.respond_file
143               ~fname:(sprintf "%s/%s" pages_dir (remove_fragment page)) outchan
144         | page -> Http_daemon.respond_forbidden ~url:page outchan)
145     | "/searchPattern" ->
146         let term_string = req#param "term" in
147         let lexbuf = Lexing.from_string term_string in
148         let (context, metasenv) = ([], []) in
149         let (dom, mk_metasenv_and_expr) =
150           CicTextualParserContext.main
151             ~context ~metasenv CicTextualLexer.token lexbuf
152         in
153         let id_to_uris_raw = req#param "aliases" in
154         let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
155         let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
156           | [] -> keys, lookup
157           | "alias" :: key :: value :: rest ->
158               let key' = CicTextualParser0.Id key in
159                parse_tokens
160                  (key'::keys)
161                  (fun id ->
162                    if id = key' then
163                      Some
164                       (CicTextualParser0.Uri (MQueryMisc.cic_textual_parser_uri_of_string value))
165                    else lookup id)
166                  rest
167           | _ -> failwith "Can't parse aliases"
168         in
169         let parse_choices choices_raw =
170           let choices = Pcre.split ~pat:";" choices_raw in
171           List.fold_left
172             (fun f x ->
173               match Pcre.split ~pat:"\\s" x with
174               | ""::id::tail
175               | id::tail when id<>"" ->
176                   (fun id' ->
177                     if id = id' then
178                       Some (List.map (fun u -> Netencoding.Url.decode u) tail)
179                     else
180                       f id')
181               | _ -> failwith "Can't parse choices")
182             (fun _ -> None)
183             choices
184         in
185         let (id_to_uris : Disambiguate.domain_and_interpretation) =
186          parse_tokens [] (fun _ -> None) tokens in
187         let id_to_choices =
188           try
189             let choices_raw = req#param "choices" in
190             parse_choices choices_raw
191           with Http_types.Param_not_found _ -> (fun _ -> None)
192         in
193         let module Chat: Disambiguate.Callbacks =
194           struct
195
196             let get_metasenv () =
197              !CicTextualParser0.metasenv
198
199             let set_metasenv metasenv =
200               CicTextualParser0.metasenv := metasenv
201
202             let output_html = prerr_endline
203
204             let interactive_user_uri_choice
205               ~selection_mode ?ok
206               ?enable_button_for_non_vars ~(title: string) ~(msg: string)
207               ~(id: string) (choices: string list)
208               =
209                 (match id_to_choices id with
210                 | Some choices -> choices
211                 | None ->
212                   let msg = Pcre.replace ~pat:"\"" ~templ:"\\\"" msg in
213                   (match selection_mode with
214                   | `SINGLE -> assert false
215                   | `EXTENDED ->
216                       iter_file
217                         (fun line ->
218                           let formatted_choices =
219                             String.concat ","
220                               (List.map (fun uri -> sprintf "\"%s\"" uri) choices)
221                           in
222                           let processed_line =
223                             apply_substs
224                               [title_tag_RE, title;
225                                choices_tag_RE, formatted_choices;
226                                msg_tag_RE, msg;
227                                id_to_uris_RE, id_to_uris_raw;
228                                id_RE, id]
229                               line
230                           in
231                           output_string outchan processed_line)
232                         interactive_user_uri_choice_TPL;
233                       raise Chat_unfinished))
234
235             let interactive_interpretation_choice interpretations =
236               let html_interpretations_labels =
237                 String.concat ", "
238                   (List.map
239                     (fun l ->
240                       "\"" ^
241                       (String.concat "<br />"
242                         (List.map
243                           (fun (id, value) ->
244                             (sprintf "alias %s %s" id value))
245                           l)) ^
246                       "\"")
247                   interpretations)
248               in
249               let html_interpretations =
250                 String.concat ", "
251                   (List.map
252                     (fun l ->
253                       "\"" ^
254                       (String.concat " "
255                         (List.map
256                           (fun (id, value) ->
257                             (sprintf "alias %s %s"
258                               id
259                               (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
260                                 value)))
261                           l)) ^
262                       "\"")
263                     interpretations)
264               in
265               iter_file
266                 (fun line ->
267                   let processed_line =
268                     apply_substs
269                       [interpretations_RE, html_interpretations;
270                        interpretations_labels_RE, html_interpretations_labels]
271                       line
272                   in
273                   output_string outchan processed_line)
274                 interactive_interpretation_choice_TPL;
275               raise Chat_unfinished
276
277             let input_or_locate_uri ~title =
278               UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
279
280           end
281         in
282         let module Disambiguate' = Disambiguate.Make (Chat) in
283         let (id_to_uris', metasenv', term') =
284           Disambiguate'.disambiguate_input
285             context metasenv dom mk_metasenv_and_expr id_to_uris
286         in
287         (match metasenv' with
288         | [] ->
289             let must = MQueryLevels2.get_constraints term' in
290             let must',only = refine_constraints must in
291             let results = MQueryGenerator.searchPattern must' only in 
292             iter_file
293               (fun line ->
294                 let new_aliases =
295                   match id_to_uris' with
296                   | (domain, f) ->
297                       String.concat ", "
298                         (List.map
299                           (fun name ->
300                             sprintf "\"alias %s cic:%s\""
301                               (match name with
302                                   CicTextualParser0.Id name -> name
303                                 | _ -> assert false (*CSC: completare *))
304                               (match f name with
305                               | None -> assert false
306                               | Some (CicTextualParser0.Uri t) ->
307                                   MQueryMisc.string_of_cic_textual_parser_uri
308                                     t
309                               | _ -> assert false (*CSC: completare *)))
310                           domain)
311                 in
312                 let processed_line =
313                   apply_substs
314                     [results_RE, text_of_result results "\n";
315                      new_aliases_RE, new_aliases]
316                     line
317                 in
318                 output_string outchan processed_line)
319               final_results_TPL
320         | _ -> (* unable to instantiate some implicit variable *)
321             Http_daemon.respond
322               ~headers:[contype]
323               ~body:"some implicit variables are still unistantiated :-("
324               outchan)
325
326     | invalid_request ->
327         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
328     if req#path <> "/getpage" then
329       Mqint.close ();
330     debug_print (sprintf "%s done!" req#path)
331   with
332   | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
333   | Http_types.Param_not_found attr_name ->
334       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
335   | exc ->
336       Http_daemon.respond
337         ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
338         outchan
339 in
340 printf "%s started and listening on port %d\n" daemon_name port;
341 printf "Current directory is %s\n" (Sys.getcwd ());
342 printf "HTML directory is %s\n" pages_dir;
343 flush stdout;
344 Unix.putenv "http_proxy" "";
345 Mqint.set_database Mqint.postgres_db;
346 Http_daemon.start' ~port callback;
347 printf "%s is terminating, bye!\n" daemon_name
348