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