]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitadaemon.ml
Matitaweb:
[helm.git] / matitaB / matita / matitadaemon.ml
1 open Printf;;
2 open Http_types;;
3
4 module Stack = Continuationals.Stack
5
6 let rt_path () = Helm_registry.get "matita.rt_base_dir" 
7
8 let libdir uid = (rt_path ()) ^ "/users/" ^ uid 
9
10 let utf8_length = Netconversion.ustring_length `Enc_utf8
11
12 (*** from matitaScript.ml ***)
13 (* let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$" *)
14
15 let eval_statement include_paths (* (buffer : GText.buffer) *) status (* script *)
16  statement
17 =
18   let ast,unparsed_text =
19     match statement with
20     | `Raw text ->
21         (* if Pcre.pmatch ~rex:only_dust_RE text then raise Margin; *)
22         let strm =
23          GrafiteParser.parsable_statement status
24           (Ulexing.from_utf8_string text) in
25         let ast = MatitaEngine.get_ast status include_paths strm in
26          ast, text
27     | `Ast (st, text) -> st, text
28   in
29   let floc = match ast with
30   | GrafiteAst.Executable (loc, _)
31   | GrafiteAst.Comment (loc, _) -> loc in
32   
33   let _,lend = HExtlib.loc_of_floc floc in 
34   let parsed_text, _parsed_text_len = 
35     HExtlib.utf8_parsed_text unparsed_text (HExtlib.floc_of_loc (0,lend)) in
36   let byte_parsed_text_len = String.length parsed_text in
37   let unparsed_txt' = 
38     String.sub unparsed_text byte_parsed_text_len 
39       (String.length unparsed_text - byte_parsed_text_len)
40   in
41   
42   let status = 
43     MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:false status ("",0,ast)
44   in 
45   (status, parsed_text, unparsed_txt'),"",(*parsed_text_len*)
46     utf8_length parsed_text
47
48 (*let save_moo status = 
49   let script = MatitaScript.current () in
50   let baseuri = status#baseuri in
51   match script#bos, script#eos with
52   | true, _ -> ()
53   | _, true ->
54      GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
55       status
56   | _ -> clean_current_baseuri status 
57 ;;*)
58     
59 let sequent_size = ref 40;;
60
61 let include_paths = ref [];;
62
63 (* <metasenv>
64  *   <meta number="...">
65  *     <metaname>...</metaname>
66  *     <goal>...</goal>
67  *   </meta>
68  *
69  *   ...
70  * </metasenv> *)
71 let output_status s =
72   let _,_,metasenv,subst,_ = s#obj in
73   let render_switch = function 
74   | Stack.Open i -> "?" ^ (string_of_int i) 
75   | Stack.Closed i -> "<S>?" ^ (string_of_int i) ^ "</S>"
76   in
77   let int_of_switch = function
78   | Stack.Open i | Stack.Closed i -> i
79   in
80   let sequent = function
81   | Stack.Open i ->
82       let meta = List.assoc i metasenv in
83       snd (ApplyTransformation.ntxt_of_cic_sequent 
84         ~metasenv ~subst ~map_unicode_to_tex:false !sequent_size s (i,meta))
85   | Stack.Closed _ -> "This goal has already been closed."
86   in
87   let render_sequent is_loc acc depth tag (pos,sw) =
88     let metano = int_of_switch sw in
89     let markup = 
90       if is_loc then
91         (match depth, pos with
92          | 0, 0 -> "<span class=\"activegoal\">" ^ (render_switch sw) ^ "</span>"
93          | 0, _ -> 
94             Printf.sprintf "<span class=\"activegoal\">|<SUB>%d</SUB>: %s</span>" pos (render_switch sw)
95          | 1, pos when Stack.head_tag s#stack = `BranchTag ->
96              Printf.sprintf "<span class=\"passivegoal\">|<SUB>%d</SUB> : %s</span>" pos (render_switch sw)
97          | _ -> render_switch sw)
98       else render_switch sw
99     in
100     let markup = 
101       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () markup in
102     let markup = "<metaname>" ^ markup ^ "</metaname>" in
103     let sequent =
104       Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false () (sequent sw)
105     in      
106     let txt0 = "<goal>" ^ sequent ^ "</goal>" in
107     "<meta number=\"" ^ (string_of_int metano) ^ "\">" ^ markup ^
108     txt0 ^ "</meta>" ^ acc
109   in
110   "<metasenv>" ^
111     (Stack.fold 
112       ~env:(render_sequent true) ~cont:(render_sequent false) 
113       ~todo:(render_sequent false) "" s#stack) ^
114     "</metasenv>"
115   (* prerr_endline ("sending metasenv:\n" ^ res); res *)
116 ;;
117
118 (* let html_of_status s =
119   let _,_,metasenv,subst,_ = s#obj in
120   let txt = List.fold_left 
121     (fun acc (nmeta,_ as meta) ->
122        let txt0 = snd (ApplyTransformation.ntxt_of_cic_sequent 
123          ~metasenv ~subst ~map_unicode_to_tex:false 80 s meta)
124        in
125        prerr_endline ("### txt0 = " ^ txt0);
126       ("<B>Goal ?" ^ (string_of_int nmeta) ^ "</B>\n" ^ txt0)::acc)
127     [] metasenv
128   in
129   String.concat "\n\n" txt
130 ;; *)
131
132 let html_of_matita s =
133   let patt1 = Str.regexp "\005" in
134   let patt2 = Str.regexp "\006" in
135   let patt3 = Str.regexp "<" in
136   let patt4 = Str.regexp ">" in
137   let res = Str.global_replace patt4 "&gt;" s in
138   let res = Str.global_replace patt3 "&lt;" res in
139   let res = Str.global_replace patt2 ">" res in
140   let res = Str.global_replace patt1 "<" res in
141   res
142 ;;
143
144 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*";;
145
146 let first_line s =
147   let s = Pcre.replace ~rex:heading_nl_RE s in
148   try
149     let nl_pos = String.index s '\n' in
150     String.sub s 0 nl_pos
151   with Not_found -> s
152 ;;
153
154 let read_file fname =
155   let chan = open_in fname in
156   let lines = ref [] in
157   (try
158      while true do
159        lines := input_line chan :: !lines
160      done;
161    with End_of_file -> close_in chan);
162   String.concat "\n" (List.rev !lines)
163 ;;
164
165 let load_index outchan =
166   let s = read_file "index.html" in
167   Http_daemon.respond ~headers:["Content-Type", "text/html"] ~code:(`Code 200) ~body:s outchan
168 ;;
169
170 let load_doc filename outchan =
171   let s = read_file filename in
172   let is_png = 
173     try String.sub filename (String.length filename - 4) 4 = ".png"
174     with Invalid_argument _ -> false
175   in
176   let contenttype = if is_png then "image/png" else "text/html" in
177   Http_daemon.respond ~headers:["Content-Type", contenttype] ~code:(`Code 200) ~body:s outchan
178 ;;
179
180 let retrieve (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
181   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
182   let env = cgi#environment in
183   (try 
184     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
185     let sid = HExtlib.unopt sid in
186     let uid = MatitaAuthentication.user_of_session sid in
187     (*
188     cgi # set_header 
189       ~cache:`No_cache 
190       ~content_type:"text/xml; charset=\"utf-8\""
191       ();
192     *)
193     let filename = libdir uid ^ "/" ^ (cgi # argument_value "file") in
194     (* prerr_endline ("reading file " ^ filename); *)
195     let body = 
196      Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false ()
197         (html_of_matita (read_file filename)) in
198      
199      (*   html_of_matita (read_file filename) in *)
200     (* prerr_endline ("sending:\nBEGIN\n" ^ body ^ "\nEND"); *)
201     let body = "<response><file>" ^ body ^ "</file></response>" in
202     let baseuri, incpaths = 
203       try 
204         let root, baseuri, _fname, _tgt = 
205           Librarian.baseuri_of_script ~include_paths:[] filename in 
206         let includes =
207          try
208           Str.split (Str.regexp " ") 
209            (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
210          with Not_found -> []
211         in
212         let rc = root :: includes in
213          List.iter (HLog.debug) rc; baseuri, rc
214        with 
215          Librarian.NoRootFor _ | Librarian.FileNotFound _ -> "",[] in
216     include_paths := incpaths;
217     let status = (MatitaAuthentication.get_status sid)#set_baseuri baseuri in
218     let history = [status] in
219     MatitaAuthentication.set_status sid status;
220     MatitaAuthentication.set_history sid history;
221     cgi # set_header 
222       ~cache:`No_cache 
223       ~content_type:"text/xml; charset=\"utf-8\""
224       ();
225     cgi#out_channel#output_string body;
226   with
227   | Not_found _ -> 
228     cgi # set_header
229       ~status:`Internal_server_error
230       ~cache:`No_cache 
231       ~content_type:"text/html; charset=\"utf-8\""
232       ());
233   cgi#out_channel#commit_work()
234 ;;
235
236 let advance0 sid text =
237   let status = MatitaAuthentication.get_status sid in
238   let status = status#reset_disambiguate_db () in
239   let (st,new_statements,new_unparsed),(* newtext TODO *) _,parsed_len =
240        try
241          eval_statement !include_paths (*buffer*) status (`Raw text)
242         with 
243         | HExtlib.Localized (_,e) -> raise e
244         (*| End_of_file -> raise Margin *)
245      in
246   let stringbuf = Ulexing.from_utf8_string new_statements in
247   let interpr = GrafiteDisambiguate.get_interpr st#disambiguate_db in
248   let outstr = ref "" in
249   ignore (SmallLexer.mk_small_printer interpr outstr stringbuf);
250   prerr_endline ("baseuri after advance = " ^ st#baseuri);
251   (* prerr_endline ("parser output: " ^ !outstr); *)
252   MatitaAuthentication.set_status sid st;
253   parsed_len, 
254     Netencoding.Html.encode ~in_enc:`Enc_utf8 ~prefer_name:false 
255       () (html_of_matita !outstr), new_unparsed, st
256
257 let register (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
258   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
259   let env = cgi#environment in
260   
261   assert (cgi#arguments <> []);
262   let uid = cgi#argument_value "userid" in
263   let userpw = cgi#argument_value "password" in
264   (try 
265     MatitaAuthentication.add_user uid userpw;
266 (*    env#set_output_header_field "Location" "/index.html" *)
267     cgi#out_channel#output_string
268      ("<html><head><meta http-equiv=\"refresh\" content=\"2;url=/login.html\">"
269      ^ "</head><body>Redirecting to login page...</body></html>")
270    with
271    | MatitaAuthentication.UsernameCollision _ ->
272       cgi#set_header
273        ~cache:`No_cache 
274        ~content_type:"text/html; charset=\"utf-8\""
275        ();
276      cgi#out_channel#output_string
277       "<html><head></head><body>Error: User id collision!</body></html>"
278    | MatitaFilesystem.SvnError msg ->
279       cgi#set_header
280        ~cache:`No_cache 
281        ~content_type:"text/html; charset=\"utf-8\""
282        ();
283      cgi#out_channel#output_string
284       ("<html><head></head><body><p>Error: Svn checkout failed!<p><p><textarea>"
285        ^ msg ^ "</textarea></p></body></html>"));
286   cgi#out_channel#commit_work()
287 ;;
288
289 let login (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
290   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
291   let env = cgi#environment in
292   
293   assert (cgi#arguments <> []);
294   let uid = cgi#argument_value "userid" in
295   let userpw = cgi#argument_value "password" in
296   let pw,_ = MatitaAuthentication.lookup_user uid in
297
298   if pw = userpw then
299    begin
300    let ft = MatitaAuthentication.read_ft uid in
301    let _ = MatitaFilesystem.html_of_library uid ft in
302     let sid = MatitaAuthentication.create_session uid in
303     (* let cookie = Netcgi.Cookie.make "session" (Uuidm.to_string sid) in
304        cgi#set_header ~set_cookies:[cookie] (); *)
305     env#set_output_header_field 
306       "Set-Cookie" ("session=" ^ (Uuidm.to_string sid));
307 (*    env#set_output_header_field "Location" "/index.html" *)
308     cgi#out_channel#output_string
309      ("<html><head><meta http-equiv=\"refresh\" content=\"2;url=/index.html\">"
310      ^ "</head><body>Redirecting to Matita page...</body></html>")
311    end
312   else
313    begin
314     cgi#set_header
315       ~cache:`No_cache 
316       ~content_type:"text/html; charset=\"utf-8\""
317       ();
318     cgi#out_channel#output_string
319       "<html><head></head><body>Authentication error</body></html>"
320    end;
321     
322   cgi#out_channel#commit_work()
323   
324 ;;
325
326 let logout (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
327   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
328   let env = cgi#environment in
329   (try 
330     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
331     let sid = HExtlib.unopt sid in
332     MatitaAuthentication.logout_user sid;
333     cgi # set_header 
334       ~cache:`No_cache 
335       ~content_type:"text/html; charset=\"utf-8\""
336       ();
337     let text = read_file (rt_path () ^ "/logout.html") in
338     cgi#out_channel#output_string text
339   with
340   | Not_found _ -> 
341     cgi # set_header
342       ~status:`Internal_server_error
343       ~cache:`No_cache 
344       ~content_type:"text/html; charset=\"utf-8\""
345       ());
346   cgi#out_channel#commit_work()
347 ;;
348
349 exception File_already_exists;;
350
351 let save (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
352   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
353   let env = cgi#environment in
354   (try 
355     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
356     let sid = HExtlib.unopt sid in
357     let status = MatitaAuthentication.get_status sid in
358     let uid = MatitaAuthentication.user_of_session sid in
359     assert (cgi#arguments <> []);
360     let locked = cgi#argument_value "locked" in
361     let unlocked = cgi#argument_value "unlocked" in
362     let dir = cgi#argument_value "dir" in
363     let rel_filename = cgi # argument_value "file" in
364     let filename = libdir uid ^ "/" ^ rel_filename in
365     let force = bool_of_string (cgi#argument_value "force") in
366
367     if ((not force) && (Sys.file_exists filename)) then 
368       raise File_already_exists;
369
370     if dir = "true" then
371       Unix.mkdir filename 0o744
372     else 
373      begin
374       let oc = open_out filename in
375       output_string oc (locked ^ unlocked);
376       close_out oc;
377       if MatitaEngine.eos status unlocked then
378        begin
379         (* prerr_endline ("serializing proof objects..."); *)
380         GrafiteTypes.Serializer.serialize 
381           ~baseuri:(NUri.uri_of_string status#baseuri) status;
382         (* prerr_endline ("adding to the commit queue..."); *)
383         MatitaFilesystem.add_user uid;
384         (* prerr_endline ("done."); *)
385        end;
386      end;
387     MatitaAuthentication.set_file_flag uid rel_filename MatitaFilesystem.MModified;
388     cgi # set_header 
389       ~cache:`No_cache 
390       ~content_type:"text/xml; charset=\"utf-8\""
391       ();
392     cgi#out_channel#output_string "<response>ok</response>"
393   with
394   | File_already_exists ->
395       cgi#out_channel#output_string "<response>cancelled</response>"
396   | Sys_error _ -> 
397     cgi # set_header
398       ~status:`Internal_server_error
399       ~cache:`No_cache 
400       ~content_type:"text/xml; charset=\"utf-8\""
401       ()
402   | e ->
403       let estr = Printexc.to_string e in
404       cgi#out_channel#output_string ("<response>" ^ estr ^ "</response>"));
405   cgi#out_channel#commit_work()
406 ;;
407
408 let initiate_commit (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
409   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
410   let env = cgi#environment in
411   (try
412     let errors = MatitaFilesystem.do_global_commit () in
413     prerr_endline ("commit errors: " ^ (String.concat " " errors));
414     cgi # set_header 
415       ~cache:`No_cache 
416       ~content_type:"text/xml; charset=\"utf-8\""
417       ();
418     cgi#out_channel#output_string "<response>ok</response>"
419   with
420   | Not_found _ -> 
421     cgi # set_header
422       ~status:`Internal_server_error
423       ~cache:`No_cache 
424       ~content_type:"text/xml; charset=\"utf-8\""
425       ());
426   cgi#out_channel#commit_work()
427 ;;
428
429 let svn_update (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
430   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
431   let env = cgi#environment in
432   let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
433   let sid = HExtlib.unopt sid in
434   let uid = MatitaAuthentication.user_of_session sid in
435   (try
436     let files,anomalies = MatitaFilesystem.update_user uid in
437     (* let changed = HExtlib.filter_map 
438         (fun (fl,n) -> if (List.mem MatitaFilesystem.Modified fl) then Some n else None) files
439       in
440       let changed = String.concat "\n" changed in
441       let anomalies = String.concat "\n" anomalies in
442       prerr_endline ("Changed:\n" ^ changed ^ "\n\nAnomalies:\n" ^ anomalies); *)
443     cgi # set_header 
444       ~cache:`No_cache 
445       ~content_type:"text/xml; charset=\"utf-8\""
446       ();
447     cgi#out_channel#output_string "<response>ok</response>"
448   with
449   | Not_found _ -> 
450     cgi # set_header
451       ~status:`Internal_server_error
452       ~cache:`No_cache 
453       ~content_type:"text/xml; charset=\"utf-8\""
454       ());
455   cgi#out_channel#commit_work()
456 ;;
457
458 (* returns the length of the executed text and an html representation of the
459  * current metasenv*)
460 let advance (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
461   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
462   let env = cgi#environment in
463   (try 
464     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
465     let sid = HExtlib.unopt sid in
466     (*
467     cgi # set_header 
468       ~cache:`No_cache 
469       ~content_type:"text/xml; charset=\"utf-8\""
470       ();
471     *)
472     let text = cgi#argument_value "body" in
473     (* prerr_endline ("body =\n" ^ text); *)
474     let history = MatitaAuthentication.get_history sid in
475     let parsed_len, new_parsed, new_unparsed, new_status = advance0 sid text in
476     MatitaAuthentication.set_history sid (new_status::history);
477     let txt = output_status new_status in
478     let body = 
479        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\">" ^
480        new_parsed ^ "</parsed>" ^ txt 
481        ^ "</response>"
482     in 
483     (* prerr_endline ("sending advance response:\n" ^ body); *)
484     cgi # set_header 
485       ~cache:`No_cache 
486       ~content_type:"text/xml; charset=\"utf-8\""
487       ();
488     cgi#out_channel#output_string body
489   with
490   | Not_found _ -> 
491     cgi # set_header
492       ~status:`Internal_server_error
493       ~cache:`No_cache 
494       ~content_type:"text/xml; charset=\"utf-8\""
495       ());
496   cgi#out_channel#commit_work()
497 ;;
498
499 let gotoBottom (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
500   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
501   let env = cgi#environment in
502   (try 
503     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
504     let sid = HExtlib.unopt sid in
505     let history = MatitaAuthentication.get_history sid in
506
507     let rec aux parsed_len parsed_txt text =
508       try
509         prerr_endline ("evaluating: " ^ first_line text);
510         let plen,new_parsed,new_unparsed,_new_status = advance0 sid text in
511         aux (parsed_len+plen) (parsed_txt ^ new_parsed) new_unparsed
512       with 
513       | End_of_file -> 
514           let status = MatitaAuthentication.get_status sid in
515           GrafiteTypes.Serializer.serialize 
516             ~baseuri:(NUri.uri_of_string status#baseuri) status;
517           if parsed_len > 0 then 
518             MatitaAuthentication.set_history sid (status::history);
519           parsed_len, parsed_txt
520       | _ -> parsed_len, parsed_txt
521     in
522     (* 
523     cgi # set_header 
524       ~cache:`No_cache 
525       ~content_type:"text/xml; charset=\"utf-8\""
526       ();
527     *)
528     let text = cgi#argument_value "body" in
529     (* prerr_endline ("body =\n" ^ text); *)
530     let parsed_len, new_parsed = aux 0 "" text in
531     let status = MatitaAuthentication.get_status sid in
532     let txt = output_status status in
533     let body = 
534        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\">" ^
535        new_parsed ^ "</parsed>" ^ txt 
536        ^ "</response>"
537     in 
538     (*let body = 
539        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
540        ^ "</response>"
541     in*) 
542     (* prerr_endline ("sending goto bottom response:\n" ^ body); *)
543     cgi # set_header 
544       ~cache:`No_cache 
545       ~content_type:"text/xml; charset=\"utf-8\""
546       ();
547     cgi#out_channel#output_string body
548    with Not_found -> cgi#set_header ~status:`Internal_server_error 
549       ~cache:`No_cache 
550       ~content_type:"text/xml; charset=\"utf-8\"" ());
551   cgi#out_channel#commit_work() 
552 ;;
553
554 let gotoTop (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
555   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
556   let env = cgi#environment in
557   prerr_endline "executing goto Top";
558   (try 
559     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
560     let sid = HExtlib.unopt sid in
561     (*
562     cgi # set_header 
563       ~cache:`No_cache 
564       ~content_type:"text/xml; charset=\"utf-8\""
565       ();
566     *)
567     let status = MatitaAuthentication.get_status sid in
568     let uid = MatitaAuthentication.user_of_session sid in
569     let baseuri = status#baseuri in
570     let new_status = new MatitaEngine.status (Some uid) baseuri in
571     prerr_endline "gototop prima della time travel";
572     NCicLibrary.time_travel new_status;
573     prerr_endline "gototop dopo della time travel";
574     let new_history = [new_status] in 
575     MatitaAuthentication.set_history sid new_history;
576     MatitaAuthentication.set_status sid new_status;
577     NCicLibrary.time_travel new_status;
578     cgi # set_header 
579       ~cache:`No_cache 
580       ~content_type:"text/xml; charset=\"utf-8\""
581       ();
582     cgi#out_channel#output_string "<response>ok</response>"
583    with _ -> 
584      (cgi#set_header ~status:`Internal_server_error 
585       ~cache:`No_cache 
586       ~content_type:"text/xml; charset=\"utf-8\"" ();
587       cgi#out_channel#output_string "<response>ok</response>"));
588   cgi#out_channel#commit_work() 
589 ;;
590
591 let retract (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
592   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
593   let env = cgi#environment in
594   (try 
595     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
596     let sid = HExtlib.unopt sid in
597     (*
598     cgi # set_header 
599       ~cache:`No_cache 
600       ~content_type:"text/xml; charset=\"utf-8\""
601       ();
602     *)
603     let history = MatitaAuthentication.get_history sid in
604     let new_history,new_status =
605        match history with
606          _::(status::_ as history) ->
607           history, status
608       | [_] -> (prerr_endline "singleton";failwith "retract")
609       | _ -> (prerr_endline "nil"; assert false) in
610     prerr_endline ("prima della time travel");
611     NCicLibrary.time_travel new_status;
612     prerr_endline ("dopo della time travel");
613     MatitaAuthentication.set_history sid new_history;
614     MatitaAuthentication.set_status sid new_status;
615     prerr_endline ("baseuri after retract = " ^ new_status#baseuri);
616     let body = output_status new_status in
617     cgi # set_header 
618       ~cache:`No_cache 
619       ~content_type:"text/xml; charset=\"utf-8\""
620       ();
621     cgi#out_channel#output_string body
622    with _ -> cgi#set_header ~status:`Internal_server_error 
623       ~cache:`No_cache 
624       ~content_type:"text/xml; charset=\"utf-8\"" ());
625   cgi#out_channel#commit_work() 
626 ;;
627
628
629 let viewLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
630   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
631   let env = cgi#environment in
632   
633     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
634     let sid = HExtlib.unopt sid in
635     (*
636     cgi # set_header 
637       ~cache:`No_cache 
638       ~content_type:"text/html; charset=\"utf-8\""
639       ();
640     *)
641     let uid = MatitaAuthentication.user_of_session sid in
642     
643     let ft = MatitaAuthentication.read_ft uid in
644     let html = MatitaFilesystem.html_of_library uid ft in
645     cgi # set_header 
646       ~cache:`No_cache 
647       ~content_type:"text/html; charset=\"utf-8\""
648       ();
649     cgi#out_channel#output_string
650       ((*
651        "<html><head>\n" ^
652        "<title>XML Tree Control</title>\n" ^
653        "<link href=\"treeview/xmlTree.css\" type=\"text/css\" rel=\"stylesheet\">\n" ^
654        "<script src=\"treeview/xmlTree.js\" type=\"text/javascript\"></script>\n" ^
655        "<body>\n" ^ *)
656        html (* ^ "\n</body></html>" *) );
657     
658     let files,anomalies = MatitaFilesystem.stat_user uid in
659     let changed = HExtlib.filter_map 
660       (fun (n,fl) -> if (List.mem MatitaFilesystem.Modified fl) then Some n else None) files
661     in
662     let changed = String.concat "\n" changed in
663     let anomalies = String.concat "\n" anomalies in
664     prerr_endline ("Changed:\n" ^ changed ^ "\n\nAnomalies:\n" ^ anomalies);
665   cgi#out_channel#commit_work()
666   
667 ;;
668
669 let resetLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
670   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
671   MatitaAuthentication.reset ();
672     cgi # set_header 
673       ~cache:`No_cache 
674       ~content_type:"text/html; charset=\"utf-8\""
675       ();
676     
677     cgi#out_channel#output_string
678       ("<html><head>\n" ^
679        "<title>Matitaweb Reset</title>\n" ^
680        "<body><H1>Reset completed</H1></body></html>");
681     cgi#out_channel#commit_work()
682
683 open Netcgi1_compat.Netcgi_types;;
684
685 (**********************************************************************)
686 (* Create the webserver                                               *)
687 (**********************************************************************)
688
689
690 let start() =
691   let (opt_list, cmdline_cfg) = Netplex_main.args() in
692
693   let use_mt = ref true in
694
695   let opt_list' =
696     [ "-mt", Arg.Set use_mt,
697       "  Use multi-threading instead of multi-processing"
698     ] @ opt_list in
699
700   Arg.parse 
701     opt_list'
702     (fun s -> raise (Arg.Bad ("Don't know what to do with: " ^ s)))
703     "usage: netplex [options]";
704   let parallelizer = 
705     if !use_mt then
706       Netplex_mt.mt()     (* multi-threading *)
707     else
708       Netplex_mp.mp() in  (* multi-processing *)
709 (*
710   let adder =
711     { Nethttpd_services.dyn_handler = (fun _ -> process1);
712       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
713       dyn_uri = None;                 (* not needed *)
714       dyn_translator = (fun _ -> ""); (* not needed *)
715       dyn_accept_all_conditionals = false;
716     } in
717 *)
718   let do_advance =
719     { Nethttpd_services.dyn_handler = (fun _ -> advance);
720       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
721       dyn_uri = None;                 (* not needed *)
722       dyn_translator = (fun _ -> ""); (* not needed *)
723       dyn_accept_all_conditionals = false;
724     } in
725   let do_retract =
726     { Nethttpd_services.dyn_handler = (fun _ -> retract);
727       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
728       dyn_uri = None;                 (* not needed *)
729       dyn_translator = (fun _ -> ""); (* not needed *)
730       dyn_accept_all_conditionals = false;
731     } in
732   let goto_bottom =
733     { Nethttpd_services.dyn_handler = (fun _ -> gotoBottom);
734       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
735       dyn_uri = None;                 (* not needed *)
736       dyn_translator = (fun _ -> ""); (* not needed *)
737       dyn_accept_all_conditionals = false;
738     } in
739   let goto_top =
740     { Nethttpd_services.dyn_handler = (fun _ -> gotoTop);
741       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
742       dyn_uri = None;                 (* not needed *)
743       dyn_translator = (fun _ -> ""); (* not needed *)
744       dyn_accept_all_conditionals = false;
745     } in
746   let retrieve =
747     { Nethttpd_services.dyn_handler = (fun _ -> retrieve);
748       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
749       dyn_uri = None;                 (* not needed *)
750       dyn_translator = (fun _ -> ""); (* not needed *)
751       dyn_accept_all_conditionals = false;
752     } in
753   let do_register =
754     { Nethttpd_services.dyn_handler = (fun _ -> register);
755       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
756       dyn_uri = None;                 (* not needed *)
757       dyn_translator = (fun _ -> ""); (* not needed *)
758       dyn_accept_all_conditionals = false;
759     } in
760   let do_login =
761     { Nethttpd_services.dyn_handler = (fun _ -> login);
762       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
763       dyn_uri = None;                 (* not needed *)
764       dyn_translator = (fun _ -> ""); (* not needed *)
765       dyn_accept_all_conditionals = false;
766     } in
767   let do_logout =
768     { Nethttpd_services.dyn_handler = (fun _ -> logout);
769       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
770       dyn_uri = None;                 (* not needed *)
771       dyn_translator = (fun _ -> ""); (* not needed *)
772       dyn_accept_all_conditionals = false;
773     } in 
774   let do_viewlib =
775     { Nethttpd_services.dyn_handler = (fun _ -> viewLib);
776       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
777       dyn_uri = None;                 (* not needed *)
778       dyn_translator = (fun _ -> ""); (* not needed *)
779       dyn_accept_all_conditionals = false;
780     } in 
781   let do_resetlib =
782     { Nethttpd_services.dyn_handler = (fun _ -> resetLib);
783       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
784       dyn_uri = None;                 (* not needed *)
785       dyn_translator = (fun _ -> ""); (* not needed *)
786       dyn_accept_all_conditionals = false;
787     } in 
788   let do_save =
789     { Nethttpd_services.dyn_handler = (fun _ -> save);
790       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
791       dyn_uri = None;                 (* not needed *)
792       dyn_translator = (fun _ -> ""); (* not needed *)
793       dyn_accept_all_conditionals = false;
794     } in 
795   let do_commit =
796     { Nethttpd_services.dyn_handler = (fun _ -> initiate_commit);
797       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
798       dyn_uri = None;                 (* not needed *)
799       dyn_translator = (fun _ -> ""); (* not needed *)
800       dyn_accept_all_conditionals = false;
801     } in 
802   let do_update =
803     { Nethttpd_services.dyn_handler = (fun _ -> svn_update);
804       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
805       dyn_uri = None;                 (* not needed *)
806       dyn_translator = (fun _ -> ""); (* not needed *)
807       dyn_accept_all_conditionals = false;
808     } in 
809   
810   
811   let nethttpd_factory = 
812     Nethttpd_plex.nethttpd_factory
813       ~handlers:[ "advance", do_advance
814                 ; "retract", do_retract
815                 ; "bottom", goto_bottom
816                 ; "top", goto_top
817                 ; "open", retrieve 
818                 ; "register", do_register
819                 ; "login", do_login 
820                 ; "logout", do_logout 
821                 ; "reset", do_resetlib
822                 ; "viewlib", do_viewlib
823                 ; "save", do_save
824                 ; "commit", do_commit
825                 ; "update", do_update]
826       () in
827   MatitaInit.initialize_all ();
828   MatitaAuthentication.deserialize ();
829   Netplex_main.startup
830     parallelizer
831     Netplex_log.logger_factories   (* allow all built-in logging styles *)
832     Netplex_workload.workload_manager_factories (* ... all ways of workload management *)
833     [ nethttpd_factory ]           (* make this nethttpd available *)
834     cmdline_cfg
835 ;;
836
837 Sys.set_signal Sys.sigpipe Sys.Signal_ignore;
838 start();;