]> matita.cs.unibo.it Git - helm.git/blob - helm/searchEngine/searchEngine.ml
aaa5f48fa34af5210bd8fd43bf2175d684bbdc98
[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 module T = MQGTypes
27 module U = MQGUtil
28 module G = MQueryGenerator
29 module C = MQIConn
30
31 open Http_types ;;
32
33 let debug = true;;
34 let debug_print s = if debug then prerr_endline s;;
35 Http_common.debug := true;;
36 (* Http_common.debug := true;; *)
37
38   (** accepted HTTP servers for ask_uwobo method forwarding *)
39 let valid_servers =
40  [ "mowgli.cs.unibo.it:58080" ; "mowgli.cs.unibo.it" ; "localhost:58080" ];;
41
42 let mqi_flags = [] (* default MathQL interpreter options *)
43
44 open Printf;;
45
46 let daemon_name = "Search Engine";;
47 let default_port = 58085;;
48 let port_env_var = "SEARCH_ENGINE_PORT";;
49
50 let pages_dir =
51   try
52     Sys.getenv "SEARCH_ENGINE_HTML_DIR"
53   with Not_found -> "html"  (* relative to searchEngine's document root *)
54 ;;
55 let interactive_user_uri_choice_TPL = pages_dir ^ "/templateambigpdq1.html";;
56 let interactive_interpretation_choice_TPL =
57   pages_dir ^ "/templateambigpdq2.html";;
58 let constraints_choice_TPL = pages_dir ^ "/constraints_choice_template.html";;
59 let final_results_TPL = pages_dir ^ "/templateambigpdq3.html";;
60
61 exception Chat_unfinished
62
63   (* build a bool from a 1-character-string *)
64 let bool_of_string' = function
65   | "0" -> false
66   | "1" -> true
67   | s -> failwith ("Can't parse a boolean from string: " ^ s)
68 ;;
69
70   (* build an int option from a string *)
71 let int_of_string' = function
72   | "_" -> None
73   | s ->
74       try
75         Some (int_of_string s)
76       with Failure "int_of_string" ->
77         failwith ("Can't parse an int option from string: " ^ s)
78 ;;
79
80   (* HTML pretty printers for mquery_generator types *)
81
82 let html_of_r_obj (pos, uri) =
83   sprintf
84     "<tr><td><input type='checkbox' name='constr_obj' checked='on'/></td><td>%s</td><td>%s</td><td>%s</td></tr>"
85     uri (U.text_of_position pos)
86     (if U.is_main_position pos then
87       sprintf "<input name='obj_depth' size='2' type='text' value='%s' />"
88         (U.text_of_depth pos "")
89     else
90       "<input type=\"hidden\" name=\"obj_depth\" />")
91 ;;
92
93 let html_of_r_rel pos =
94   sprintf
95     "<tr><td><input type='checkbox' name='constr_rel' checked='on'/></td><td>%s</td><td><input name='rel_depth' size='2' type='text' value='%s' /></td></tr>"
96     (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
97 ;;
98
99 let html_of_r_sort (pos, sort) =
100   sprintf
101     "<tr><td><input type='checkbox' name='constr_sort' checked='on'/></td><td>%s</td><td>%s</td><td><input name='sort_depth' size='2' type='text' value='%s'/></td></tr>"
102     (U.text_of_sort sort) (U.text_of_position (pos:>T.full_position)) (U.text_of_depth (pos:>T.full_position) "")
103 ;;
104
105   (** pretty print a MathQL query result to an HELM theory file *)
106 let theory_of_result result =
107  let results_no = List.length result in
108   if results_no > 0 then
109    let mode = if results_no > 10 then "linkonly" else "typeonly" in
110    let results =
111     let idx = ref (results_no + 1) in
112      List.fold_right
113       (fun (uri,attrs) i ->
114         decr idx ;
115         "<tr><td valign=\"top\">" ^ string_of_int !idx ^ ".</td><td><ht:OBJECT uri=\"" ^ uri ^ "\" mode=\"" ^ mode ^ "\"/></td></tr>" ^  i
116       ) result ""
117    in
118     "<h1>Query Results:</h1><table xmlns:ht=\"http://www.cs.unibo.it/helm/namespaces/helm-theory\">" ^ results ^ "</table>"
119   else
120     "<h1>Query Results:</h1><p>No results found!</p>"
121 ;;
122
123 let pp_result result =
124  "<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>"
125 ;;
126
127   (** chain application of Pcre substitutions *)
128 let rec apply_substs substs line =
129   match substs with
130   | [] -> line
131   | (rex, templ) :: rest -> apply_substs rest (Pcre.replace ~rex ~templ line)
132   (** fold like function on files *)
133 let fold_file f init fname =
134   let inchan = open_in fname in
135   let rec fold_lines' value =
136     try 
137       let line = input_line inchan in 
138       fold_lines' (f value line)
139     with End_of_file -> value
140   in
141   let res = (try fold_lines' init with e -> (close_in inchan; raise e)) in
142   close_in inchan;
143   res
144   (** iter like function on files *)
145 let iter_file f = fold_file (fun _ line -> f line) ()
146
147 let (title_tag_RE, choices_tag_RE, msg_tag_RE, id_to_uris_RE, id_RE,
148     interpretations_RE, interpretations_labels_RE, results_RE, new_aliases_RE,
149     form_RE, variables_initialization_RE)
150   =
151   (Pcre.regexp "@TITLE@", Pcre.regexp "@CHOICES@", Pcre.regexp "@MSG@",
152   Pcre.regexp "@ID_TO_URIS@", Pcre.regexp "@ID@",
153   Pcre.regexp "@INTERPRETATIONS@", Pcre.regexp "@INTERPRETATIONS_LABELS@",
154   Pcre.regexp "@RESULTS@", Pcre.regexp "@NEW_ALIASES@", Pcre.regexp "@FORM@",
155   Pcre.regexp "@VARIABLES_INITIALIZATION@")
156 let server_and_port_url_RE = Pcre.regexp "^http://([^/]+)/.*$"
157
158 exception NotAnInductiveDefinition
159
160 let port =
161   try
162     int_of_string (Sys.getenv port_env_var)
163   with
164   | Not_found -> default_port
165   | Failure "int_of_string" ->
166       prerr_endline "Warning: invalid port, reverting to default";
167       default_port
168 ;;
169
170 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>";;
171
172 let bad_request body outchan =
173   Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
174 ;;
175
176 let contype = "Content-Type", "text/html";;
177
178 (* SEARCH ENGINE functions *)
179
180 let refine_constraints ((constr_obj:T.r_obj list), (constr_rel:T.r_rel list), (constr_sort:T.r_sort list)) =
181  function
182     "/searchPattern" ->
183       U.universe_for_search_pattern,
184        (constr_obj, constr_rel, constr_sort),
185        (Some constr_obj, Some constr_rel, Some constr_sort)
186   | "/matchConclusion" ->
187       let constr_obj' =
188        List.map
189         (function (pos, uri) -> U.set_full_position pos None, uri)
190         (List.filter
191           (function (pos, _) -> U.is_conclusion pos)
192           constr_obj)
193       in
194        U.universe_for_match_conclusion,
195        (*CSC: we must select the must constraints here!!! *)
196        (constr_obj',[],[]),(Some constr_obj', None, None)
197   | _ -> assert false
198 ;;
199
200 let get_constraints term =
201  function
202     "/locateInductivePrinciple" ->
203       let uri = 
204        match term with
205           Cic.MutInd (uri,t,_) -> MQueryUtil.string_of_uriref (uri,[t])
206         | _ -> raise NotAnInductiveDefinition
207       in
208       let constr_obj =
209        [(`InHypothesis, uri); (`MainHypothesis (Some 0), uri)]
210       in
211       let constr_rel = [`MainConclusion None] in
212       let constr_sort = [(`MainHypothesis (Some 1), T.Prop)] in
213        U.universe_for_search_pattern,
214         (constr_obj, constr_rel, constr_sort), (None,None,None)
215   | req_path ->
216      let must = MQueryLevels2.get_constraints term in
217       refine_constraints must req_path
218 ;;
219
220 (*
221   format:
222     <must_obj> ':' <must_rel> ':' <must_sort> ':' <only_obj> ':' <only_rel> ':' <only_sort>
223
224     <must_*> ::= ('0'|'1') ('_'|<int>) (',' ('0'|'1') ('_'|<int>))*
225     <only> ::= '0'|'1'
226 *)
227 let add_user_constraints ~constraints
228  ((obj, rel, sort), (only_obj, only_rel, only_sort))
229 =
230   let parse_must s =
231     let l = Pcre.split ~pat:"," s in
232     (try
233       List.map
234         (fun s ->
235           let subs = Pcre.extract ~pat:"^(.)(\\d+|_)$" s in
236           (bool_of_string' subs.(1), int_of_string' subs.(2)))
237         l
238      with
239       Not_found -> failwith ("Can't parse constraint string: " ^ constraints)
240     )
241   in
242     (* to be used on "obj" *)
243   let add_user_must33 user_must must =
244     List.map2
245      (fun (b, i) (p, u) ->
246        if b then Some (U.set_full_position p i, u) else None)
247      user_must must
248   in
249     (* to be used on "rel" *)
250   let add_user_must22 user_must must =
251     List.map2
252      (fun (b, i) p -> if b then Some (U.set_main_position p i) else None)
253      user_must must
254   in
255     (* to be used on "sort" *)
256   let add_user_must32 user_must must =
257     List.map2
258      (fun (b, i) (p, s)-> if b then Some (U.set_main_position p i, s) else None)
259      user_must must
260   in
261   match Pcre.split ~pat:":" constraints with
262   | [user_obj;user_rel;user_sort;user_only_obj;user_only_rel;user_only_sort] ->
263       let
264        (user_obj,user_rel,user_sort,user_only_obj,user_only_rel,user_only_sort)
265       =
266         (parse_must user_obj,
267         parse_must user_rel,
268         parse_must user_sort,
269         bool_of_string' user_only_obj,
270         bool_of_string' user_only_rel,
271         bool_of_string' user_only_sort)
272       in
273       let only' =
274        (if user_only_obj  then only_obj else None),
275        (if user_only_rel  then only_rel else None),
276        (if user_only_sort then only_sort else None)
277       in
278       let must' =
279        let rec filter_some =
280         function
281            [] -> []
282          | None::tl -> filter_some tl
283          | (Some x)::tl -> x::(filter_some tl) 
284        in
285         filter_some (add_user_must33 user_obj obj),
286         filter_some (add_user_must22 user_rel rel),
287         filter_some (add_user_must32 user_sort sort)
288       in
289       (must', only')
290   | _ -> failwith ("Can't parse constraint string: " ^ constraints)
291 in
292
293 (* HTTP DAEMON CALLBACK *)
294
295 let callback (req: Http_types.request) outchan =
296   try
297     debug_print (sprintf "Received request: %s" req#path);
298     (match req#path with
299     | "/execute" ->
300         let mqi_handle = C.init mqi_flags debug_print in 
301         let query_string = req#param "query" in
302         let lexbuf = Lexing.from_string query_string in
303         let query = MQueryUtil.query_of_text lexbuf in
304         let result = MQueryInterpreter.execute mqi_handle query in
305         let result_string = pp_result result in
306               C.close mqi_handle;
307         Http_daemon.respond ~body:result_string ~headers:[contype] outchan
308     | "/locate" ->
309         let mqi_handle = C.init mqi_flags debug_print in
310         let id = req#param "id" in
311         let query = G.locate id in
312         let result = MQueryInterpreter.execute mqi_handle query in
313               C.close mqi_handle;
314         Http_daemon.respond ~headers:[contype] ~body:(pp_result result) outchan
315     | "/getpage" ->
316         (* TODO implement "is_permitted" *)
317         (let is_permitted _ = true in
318         let remove_fragment uri = Pcre.replace ~pat:"#.*" uri in
319         let page = remove_fragment (req#param "url") in
320         let preprocess =
321           (try
322             bool_of_string (req#param "preprocess")
323           with Invalid_argument _ | Http_types.Param_not_found _ -> false)
324         in
325         (match page with
326         | page when is_permitted page ->
327             (let fname = sprintf "%s/%s" pages_dir (remove_fragment page) in
328             Http_daemon.send_basic_headers ~code:200 outchan;
329             Http_daemon.send_header "Content-Type" "text/html" outchan;
330             Http_daemon.send_CRLF outchan;
331             if preprocess then begin
332               iter_file
333                 (fun line ->
334                   output_string outchan
335                     ((apply_substs
336                        (List.map
337                          (function (key,value) ->
338                            let key' =
339                             (Pcre.extract ~pat:"param\\.(.*)" key).(1)
340                            in
341                             Pcre.regexp ("@" ^ key' ^ "@"), value
342                          )
343                          (List.filter
344                            (fun (key,_) as p-> Pcre.pmatch ~pat:"^param\\." key)
345                            req#params)
346                        )
347                        line) ^
348                     "\n"))
349                 fname
350             end else
351               Http_daemon.send_file ~src:(FileSrc fname) outchan)
352         | page -> Http_daemon.respond_forbidden ~url:page outchan))
353     | "/ask_uwobo" ->
354       let url = req#param "url" in
355       let server_and_port =
356         (Pcre.extract ~rex:server_and_port_url_RE url).(1)
357       in
358       if List.mem server_and_port valid_servers then
359         Http_daemon.respond
360           ~headers:["Content-Type", "text/html"]
361           ~body:(Http_client.Convenience.http_get url)
362           outchan
363       else
364         Http_daemon.respond
365           ~body:(pp_error ("Untrusted UWOBO server: " ^ server_and_port))
366           outchan
367     | "/searchPattern"
368     | "/matchConclusion"
369     | "/locateInductivePrinciple" ->
370         let mqi_handle = C.init mqi_flags debug_print in
371         let term_string = req#param "term" in
372         let lexbuf = Lexing.from_string term_string in
373         let (context, metasenv) = ([], []) in
374         let (dom, mk_metasenv_and_expr) =
375           CicTextualParserContext.main
376             ~context ~metasenv CicTextualLexer.token lexbuf
377         in
378         let id_to_uris_raw = req#param "aliases" in
379         let tokens = Pcre.split ~pat:"\\s" id_to_uris_raw in
380         let rec parse_tokens keys lookup = function (* TODO spostarla fuori *)
381           | [] -> keys, lookup
382           | "alias" :: key :: value :: rest ->
383               let key' = CicTextualParser0.Id key in
384                parse_tokens
385                  (key'::keys)
386                  (fun id ->
387                    if id = key' then
388                      Some
389                       (CicTextualParser0.Uri (MQueryMisc.cic_textual_parser_uri_of_string value))
390                    else lookup id)
391                  rest
392           | _ -> failwith "Can't parse aliases"
393         in
394         let parse_choices choices_raw =
395           let choices = Pcre.split ~pat:";" choices_raw in
396           List.fold_left
397             (fun f x ->
398               match Pcre.split ~pat:"\\s" x with
399               | ""::id::tail
400               | id::tail when id<>"" ->
401                   (fun id' ->
402 prerr_endline ("#### " ^ id ^ " :=");
403 List.iter (fun u -> prerr_endline ("<" ^ Netencoding.Url.decode u ^ ">")) tail;
404                     if id = id' then
405                       Some (List.map (fun u -> Netencoding.Url.decode u) tail)
406                     else
407                       f id')
408               | _ -> failwith "Can't parse choices")
409             (fun _ -> None)
410             choices
411         in
412         let (id_to_uris : Disambiguate.domain_and_interpretation) =
413          parse_tokens [] (fun _ -> None) tokens in
414         let id_to_choices =
415           try
416             let choices_raw = req#param "choices" in
417             parse_choices choices_raw
418           with Http_types.Param_not_found _ -> (fun _ -> None)
419         in
420         let module Chat: Disambiguate.Callbacks =
421           struct
422
423             let get_metasenv () =
424              !CicTextualParser0.metasenv
425
426             let set_metasenv metasenv =
427               CicTextualParser0.metasenv := metasenv
428
429             let output_html = prerr_endline
430
431             let interactive_user_uri_choice
432               ~selection_mode ?ok
433               ?enable_button_for_non_vars ~(title: string) ~(msg: string)
434               ~(id: string) (choices: string list)
435               =
436                 (match id_to_choices id with
437                 | Some choices -> choices
438                 | None ->
439                   let msg = Pcre.replace ~pat:"\'" ~templ:"\\\'" msg in
440                   (match selection_mode with
441                   | `SINGLE -> assert false
442                   | `EXTENDED ->
443                       Http_daemon.send_basic_headers ~code:200 outchan ;
444                       Http_daemon.send_CRLF outchan ;
445                       iter_file
446                         (fun line ->
447                           let formatted_choices =
448                             String.concat ","
449                               (List.map (fun uri -> sprintf "\'%s\'" uri) choices)
450                           in
451                           let processed_line =
452                             apply_substs
453                               [title_tag_RE, title;
454                                choices_tag_RE, formatted_choices;
455                                msg_tag_RE, msg;
456                                id_to_uris_RE, id_to_uris_raw;
457                                id_RE, id]
458                               line
459                           in
460                           output_string outchan (processed_line ^ "\n"))
461                         interactive_user_uri_choice_TPL;
462                       raise Chat_unfinished))
463
464             let interactive_interpretation_choice interpretations =
465               let html_interpretations_labels =
466                 String.concat ", "
467                   (List.map
468                     (fun l ->
469                       "\'" ^
470                       (String.concat "<br />"
471                         (List.map
472                           (fun (id, value) ->
473                             (sprintf "alias %s %s" id value))
474                           l)) ^
475                       "\'")
476                   interpretations)
477               in
478               let html_interpretations =
479                 String.concat ", "
480                   (List.map
481                     (fun l ->
482                       "\'" ^
483                       (String.concat " "
484                         (List.map
485                           (fun (id, value) ->
486                             (sprintf "alias %s %s"
487                               id
488                               (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
489                                 value)))
490                           l)) ^
491                       "\'")
492                     interpretations)
493               in
494               Http_daemon.send_basic_headers ~code:200 outchan ;
495               Http_daemon.send_CRLF outchan ;
496               iter_file
497                 (fun line ->
498                   let processed_line =
499                     apply_substs
500                       [interpretations_RE, html_interpretations;
501                        interpretations_labels_RE, html_interpretations_labels]
502                       line
503                   in
504                   output_string outchan (processed_line ^ "\n"))
505                 interactive_interpretation_choice_TPL;
506               raise Chat_unfinished
507
508             let input_or_locate_uri ~title =
509               UriManager.uri_of_string "cic:/Coq/Init/DataTypes/nat_ind.con"
510
511           end
512         in
513         let module Disambiguate' = Disambiguate.Make (Chat) in
514         let (id_to_uris', metasenv', term') =
515           Disambiguate'.disambiguate_input mqi_handle
516             context metasenv dom mk_metasenv_and_expr id_to_uris
517         in
518         (match metasenv' with
519         | [] ->
520             let universe,
521                 ((must_obj, must_rel, must_sort) as must'),
522                 ((only_obj, only_rel, only_sort) as only) =
523               get_constraints term' req#path
524             in
525             let must'', only' =
526               (try
527                 add_user_constraints
528                   ~constraints:(req#param "constraints")
529                   (must', only)
530               with Http_types.Param_not_found _ ->
531                 let variables =
532                  "var aliases = '" ^ id_to_uris_raw ^ "';\n" ^
533                  "var constr_obj_len = " ^
534                   string_of_int (List.length must_obj) ^ ";\n" ^
535                  "var constr_rel_len = " ^
536                   string_of_int (List.length must_rel) ^ ";\n" ^
537                  "var constr_sort_len = " ^
538                   string_of_int (List.length must_sort) ^ ";\n" in
539                 let form =
540                   (if must_obj = [] then "" else
541                     "<h4>Obj constraints</h4>" ^
542                     "<table>" ^
543                     (String.concat "\n" (List.map html_of_r_obj must_obj)) ^
544                     "</table>" ^
545                     (* The following three lines to make Javascript create *)
546                     (* the constr_obj[] and obj_depth[] arrays even if we  *)
547                     (* have only one real entry.                           *)
548                     "<input type=\"hidden\" name=\"constr_obj\" />" ^
549                     "<input type=\"hidden\" name=\"obj_depth\" />") ^
550                   (if must_rel = [] then "" else
551                    "<h4>Rel constraints</h4>" ^
552                    "<table>" ^
553                    (String.concat "\n" (List.map html_of_r_rel must_rel)) ^
554                    "</table>" ^
555                     (* The following two lines to make Javascript create *)
556                     (* the constr_rel[] and rel_depth[] arrays even if   *)
557                     (* we have only one real entry.                      *)
558                     "<input type=\"hidden\" name=\"constr_rel\" />" ^
559                     "<input type=\"hidden\" name=\"rel_depth\" />") ^
560                   (if must_sort = [] then "" else
561                     "<h4>Sort constraints</h4>" ^
562                     "<table>" ^
563                     (String.concat "\n" (List.map html_of_r_sort must_sort)) ^
564                     "</table>" ^
565                     (* The following two lines to make Javascript create *)
566                     (* the constr_sort[] and sort_depth[] arrays even if *)
567                     (* we have only one real entry.                      *)
568                     "<input type=\"hidden\" name=\"constr_sort\" />" ^
569                     "<input type=\"hidden\" name=\"sort_depth\" />") ^
570                     "<h4>Only constraints</h4>" ^
571                     "Enforce Only constraints for objects: " ^
572                       "<input type='checkbox' name='only_obj'" ^
573                       (if only_obj = None then "" else " checked='yes'") ^ " /><br />" ^
574                     "Enforce Rel constraints for objects: " ^
575                       "<input type='checkbox' name='only_rel'" ^
576                       (if only_rel = None then "" else " checked='yes'") ^ " /><br />" ^
577                     "Enforce Sort constraints for objects: " ^
578                       "<input type='checkbox' name='only_sort'" ^
579                       (if only_sort = None then "" else " checked='yes'") ^ " /><br />"
580                 in
581                 Http_daemon.send_basic_headers ~code:200 outchan ;
582                 Http_daemon.send_CRLF outchan ;
583                 iter_file
584                   (fun line ->
585                     let processed_line =
586                       apply_substs
587                        [form_RE, form ;
588                         variables_initialization_RE, variables] line
589                     in
590                     output_string outchan (processed_line ^ "\n"))
591                   constraints_choice_TPL;
592                   raise Chat_unfinished)
593             in
594             let query =
595              G.query_of_constraints (Some universe) must'' only'
596             in
597                   let results = MQueryInterpreter.execute mqi_handle query in 
598              Http_daemon.send_basic_headers ~code:200 outchan ;
599              Http_daemon.send_CRLF outchan ;
600              iter_file
601                (fun line ->
602                  let new_aliases =
603                    match id_to_uris' with
604                    | (domain, f) ->
605                        String.concat ", "
606                          (List.map
607                            (fun name ->
608                              sprintf "\'alias %s cic:%s\'"
609                                (match name with
610                                    CicTextualParser0.Id name -> name
611                                  | _ -> assert false (*CSC: completare *))
612                                (match f name with
613                                | None -> assert false
614                                | Some (CicTextualParser0.Uri t) ->
615                                    MQueryMisc.string_of_cic_textual_parser_uri
616                                      t
617                                | _ -> assert false (*CSC: completare *)))
618                            domain)
619                  in
620                  let processed_line =
621                    apply_substs
622                      [results_RE, theory_of_result results ;
623                       new_aliases_RE, new_aliases]
624                      line
625                  in
626                  output_string outchan (processed_line ^ "\n"))
627                final_results_TPL
628         | _ -> (* unable to instantiate some implicit variable *)
629             Http_daemon.respond
630               ~headers:[contype]
631               ~body:"some implicit variables are still unistantiated :-("
632               outchan);
633             C.close mqi_handle
634     | invalid_request ->
635         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan);
636     debug_print (sprintf "%s done!" req#path)
637   with
638   | Chat_unfinished -> prerr_endline "Chat unfinished, Try again!"
639   | Http_types.Param_not_found attr_name ->
640       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
641   | exc ->
642       Http_daemon.respond
643         ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
644         outchan
645 in
646 printf "%s started and listening on port %d\n" daemon_name port;
647 printf "Current directory is %s\n" (Sys.getcwd ());
648 printf "HTML directory is %s\n" pages_dir;
649 flush stdout;
650 Unix.putenv "http_proxy" "";
651 Http_daemon.start' ~port callback;
652 printf "%s is terminating, bye!\n" daemon_name
653