]> matita.cs.unibo.it Git - helm.git/blob - helm/searchEngine/searchEngine.ml
Added preprocess feature to "getpage" method. Using this feature you can
[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     processorURL_RE)
103   =
104   (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
105   Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
106   Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
107   Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@",
108   Pcre.regexp "@processorURL@")
109 let server_and_port_url_RE = Pcre.regexp "^http://([^/]+)/.*$"
110
111 let port =
112   try
113     int_of_string (Sys.getenv port_env_var)
114   with
115   | Not_found -> default_port
116   | Failure "int_of_string" ->
117       prerr_endline "Warning: invalid port, reverting to default";
118       default_port
119 in
120 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>" in
121 let bad_request body outchan =
122   Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
123 in
124 let contype = "Content-Type", "text/html" in
125
126 (* SEARCH ENGINE functions *)
127
128 let refine_constraints (x, y, z) = (x, y, z), (Some x, Some y, Some z) in
129
130 (* HTTP DAEMON CALLBACK *)
131
132 let callback (req: Http_types.request) outchan =
133   try
134     debug_print (sprintf "Received request: %s" req#path);
135     if req#path <> "/getpage" then
136       Mqint.init postgresConnectionString;
137     (match req#path with
138     | "/execute" ->
139         let query_string = req#param "query" in
140         let lexbuf = Lexing.from_string query_string in
141         let query = MQueryUtil.query_of_text lexbuf in
142         let result = MQueryGenerator.execute_query query in
143         let result_string = pp_result result in
144         Http_daemon.respond ~body:result_string ~headers:[contype] outchan
145     | "/locate" ->
146         let id = req#param "id" in
147         let result = MQueryGenerator.locate id in
148         Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
149     | "/getpage" ->
150         (* TODO implement "is_permitted" *)
151         (let is_permitted _ = true in
152         let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
153         let page = remove_fragment (req#param "url") in
154         let preprocess =
155           (try
156             bool_of_string (req#param "preprocess")
157           with Invalid_argument _ | Http_types.Param_not_found _ -> false)
158         in
159         (match page with
160         | page when is_permitted page ->
161             let fname = sprintf "%s/%s" pages_dir (remove_fragment page) in
162             if preprocess then begin
163               Http_daemon.send_basic_headers ~code:200 outchan;
164               Http_daemon.send_CRLF outchan;
165               iter_file
166                 (fun line ->
167                   output_string outchan
168                     ((apply_substs
169                       [processorURL_RE, req#param "processorURL"] line) ^
170                     "\n"))
171                 fname
172             end else
173               Http_daemon.respond_file ~fname outchan
174         | page -> Http_daemon.respond_forbidden ~url:page outchan))
175     | "/ask_uwobo" ->
176       let url = req#param "url" in
177       let server_and_port =
178         (Pcre.extract ~rex:server_and_port_url_RE url).(1)
179       in
180       if List.mem server_and_port valid_servers then
181         Http_daemon.respond
182           ~body:(Http_client.Convenience.http_get url)
183           outchan
184       else
185         Http_daemon.respond
186           ~body:(pp_error ("Invalid UWOBO server: " ^ server_and_port))
187           outchan
188     | "/searchPattern" ->
189         let term_string = req#param "term" in
190         let lexbuf = Lexing.from_string term_string in
191         let (context, metasenv) = ([], []) in
192         let (dom, mk_metasenv_and_expr) =
193           CicTextualParserContext.main
194             ~context ~metasenv CicTextualLexer.token lexbuf
195         in
196         let id_to_uris_raw = req#param "aliases" in
197         let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
198         let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
199           | [] -> keys, lookup
200           | "alias" :: key :: value :: rest ->
201               let key' = CicTextualParser0.Id key in
202                parse_tokens
203                  (key'::keys)
204                  (fun id ->
205                    if id = key' then
206                      Some
207                       (CicTextualParser0.Uri (MQueryMisc.cic_textual_parser_uri_of_string value))
208                    else lookup id)
209                  rest
210           | _ -> failwith "Can't parse aliases"
211         in
212         let parse_choices choices_raw =
213           let choices = Pcre.split ~pat:";" choices_raw in
214           List.fold_left
215             (fun f x ->
216               match Pcre.split ~pat:"\\s" x with
217               | ""::id::tail
218               | id::tail when id<>"" ->
219                   (fun id' ->
220 prerr_endline ("#### " ^ id ^ " :=");
221 List.iter (fun u -> prerr_endline ("<" ^ Netencoding.Url.decode u ^ ">")) tail;
222                     if id = id' then
223                       Some (List.map (fun u -> Netencoding.Url.decode u) tail)
224                     else
225                       f id')
226               | _ -> failwith "Can't parse choices")
227             (fun _ -> None)
228             choices
229         in
230         let (id_to_uris : Disambiguate.domain_and_interpretation) =
231          parse_tokens [] (fun _ -> None) tokens in
232         let id_to_choices =
233           try
234             let choices_raw = req#param "choices" in
235             parse_choices choices_raw
236           with Http_types.Param_not_found _ -> (fun _ -> None)
237         in
238         let module Chat: Disambiguate.Callbacks =
239           struct
240
241             let get_metasenv () =
242              !CicTextualParser0.metasenv
243
244             let set_metasenv metasenv =
245               CicTextualParser0.metasenv := metasenv
246
247             let output_html = prerr_endline
248
249             let interactive_user_uri_choice
250               ~selection_mode ?ok
251               ?enable_button_for_non_vars ~(title: string) ~(msg: string)
252               ~(id: string) (choices: string list)
253               =
254                 (match id_to_choices id with
255                 | Some choices -> choices
256                 | None ->
257                   let msg = Pcre.replace ~pat:"\"" ~templ:"\\\"" msg in
258                   (match selection_mode with
259                   | `SINGLE -> assert false
260                   | `EXTENDED ->
261                       Http_daemon.send_basic_headers ~code:200 outchan ;
262                       Http_daemon.send_CRLF outchan ;
263                       iter_file
264                         (fun line ->
265                           let formatted_choices =
266                             String.concat ","
267                               (List.map (fun uri -> sprintf "\"%s\"" uri) choices)
268                           in
269                           let processed_line =
270                             apply_substs
271                               [title_tag_RE, title;
272                                choices_tag_RE, formatted_choices;
273                                msg_tag_RE, msg;
274                                id_to_uris_RE, id_to_uris_raw;
275                                id_RE, id]
276                               line
277                           in
278                           output_string outchan (processed_line ^ "\n"))
279                         interactive_user_uri_choice_TPL;
280                       raise Chat_unfinished))
281
282             let interactive_interpretation_choice interpretations =
283               let html_interpretations_labels =
284                 String.concat ", "
285                   (List.map
286                     (fun l ->
287                       "\"" ^
288                       (String.concat "<br />"
289                         (List.map
290                           (fun (id, value) ->
291                             (sprintf "alias %s %s" id value))
292                           l)) ^
293                       "\"")
294                   interpretations)
295               in
296               let html_interpretations =
297                 String.concat ", "
298                   (List.map
299                     (fun l ->
300                       "\"" ^
301                       (String.concat " "
302                         (List.map
303                           (fun (id, value) ->
304                             (sprintf "alias %s %s"
305                               id
306                               (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
307                                 value)))
308                           l)) ^
309                       "\"")
310                     interpretations)
311               in
312               Http_daemon.send_basic_headers ~code:200 outchan ;
313               Http_daemon.send_CRLF outchan ;
314               iter_file
315                 (fun line ->
316                   let processed_line =
317                     apply_substs
318                       [interpretations_RE, html_interpretations;
319                        interpretations_labels_RE, html_interpretations_labels]
320                       line
321                   in
322                   output_string outchan (processed_line ^ "\n"))
323                 interactive_interpretation_choice_TPL;
324               raise Chat_unfinished
325
326             let input_or_locate_uri ~title =
327               UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
328
329           end
330         in
331         let module Disambiguate' = Disambiguate.Make (Chat) in
332         let (id_to_uris', metasenv', term') =
333           Disambiguate'.disambiguate_input
334             context metasenv dom mk_metasenv_and_expr id_to_uris
335         in
336         (match metasenv' with
337         | [] ->
338             let must = MQueryLevels2.get_constraints term' in
339             let must',only = refine_constraints must in
340             let results = MQueryGenerator.searchPattern must' only in 
341             Http_daemon.send_basic_headers ~code:200 outchan ;
342             Http_daemon.send_CRLF outchan ;
343             iter_file
344               (fun line ->
345                 let new_aliases =
346                   match id_to_uris' with
347                   | (domain, f) ->
348                       String.concat ", "
349                         (List.map
350                           (fun name ->
351                             sprintf "\"alias %s cic:%s\""
352                               (match name with
353                                   CicTextualParser0.Id name -> name
354                                 | _ -> assert false (*CSC: completare *))
355                               (match f name with
356                               | None -> assert false
357                               | Some (CicTextualParser0.Uri t) ->
358                                   MQueryMisc.string_of_cic_textual_parser_uri
359                                     t
360                               | _ -> assert false (*CSC: completare *)))
361                           domain)
362                 in
363                 let processed_line =
364                   apply_substs
365                     [results_RE, theory_of_result results ;
366                      new_aliases_RE, new_aliases]
367                     line
368                 in
369                 output_string outchan (processed_line ^ "\n"))
370               final_results_TPL
371         | _ -> (* unable to instantiate some implicit variable *)
372             Http_daemon.respond
373               ~headers:[contype]
374               ~body:"some implicit variables are still unistantiated :-("
375               outchan)
376
377     | invalid_request ->
378         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
379     if req#path <> "/getpage" then
380       Mqint.close ();
381     debug_print (sprintf "%s done!" req#path)
382   with
383   | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
384   | Http_types.Param_not_found attr_name ->
385       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
386   | exc ->
387       Http_daemon.respond
388         ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
389         outchan
390 in
391 printf "%s started and listening on port %d\n" daemon_name port;
392 printf "Current directory is %s\n" (Sys.getcwd ());
393 printf "HTML directory is %s\n" pages_dir;
394 flush stdout;
395 Unix.putenv "http_proxy" "";
396 Mqint.set_database Mqint.postgres_db;
397 Http_daemon.start' ~port callback;
398 printf "%s is terminating, bye!\n" daemon_name
399