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