]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitadaemon.ml
Matitaweb: implementation of file-flagging for keeping track of modified files
[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 
388       [rel_filename, Some MatitaFilesystem.MModified];
389     cgi # set_header 
390       ~cache:`No_cache 
391       ~content_type:"text/xml; charset=\"utf-8\""
392       ();
393     cgi#out_channel#output_string "<response>ok</response>"
394   with
395   | File_already_exists ->
396       cgi#out_channel#output_string "<response>cancelled</response>"
397   | Sys_error _ -> 
398     cgi # set_header
399       ~status:`Internal_server_error
400       ~cache:`No_cache 
401       ~content_type:"text/xml; charset=\"utf-8\""
402       ()
403   | e ->
404       let estr = Printexc.to_string e in
405       cgi#out_channel#output_string ("<response>" ^ estr ^ "</response>"));
406   cgi#out_channel#commit_work()
407 ;;
408
409 let initiate_commit (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
410   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
411   let env = cgi#environment in
412   (try
413     let errors = MatitaFilesystem.do_global_commit () in
414     prerr_endline ("commit errors: " ^ (String.concat " " errors));
415     cgi # set_header 
416       ~cache:`No_cache 
417       ~content_type:"text/xml; charset=\"utf-8\""
418       ();
419     cgi#out_channel#output_string "<response>ok</response>"
420   with
421   | Not_found _ -> 
422     cgi # set_header
423       ~status:`Internal_server_error
424       ~cache:`No_cache 
425       ~content_type:"text/xml; charset=\"utf-8\""
426       ());
427   cgi#out_channel#commit_work()
428 ;;
429
430 let svn_update (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
431   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
432   let env = cgi#environment in
433   let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
434   let sid = HExtlib.unopt sid in
435   let uid = MatitaAuthentication.user_of_session sid in
436   (try
437     let files,anomalies = MatitaFilesystem.update_user uid in
438     (* let changed = HExtlib.filter_map 
439         (fun (fl,n) -> if (List.mem MatitaFilesystem.Modified fl) then Some n else None) files
440       in
441       let changed = String.concat "\n" changed in
442       let anomalies = String.concat "\n" anomalies in
443       prerr_endline ("Changed:\n" ^ changed ^ "\n\nAnomalies:\n" ^ anomalies); *)
444     MatitaAuthentication.set_file_flag uid files;
445     cgi # set_header 
446       ~cache:`No_cache 
447       ~content_type:"text/xml; charset=\"utf-8\""
448       ();
449     cgi#out_channel#output_string "<response>ok</response>"
450   with
451   | Not_found _ -> 
452     cgi # set_header
453       ~status:`Internal_server_error
454       ~cache:`No_cache 
455       ~content_type:"text/xml; charset=\"utf-8\""
456       ());
457   cgi#out_channel#commit_work()
458 ;;
459
460 (* returns the length of the executed text and an html representation of the
461  * current metasenv*)
462 let advance (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
463   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
464   let env = cgi#environment in
465   (try 
466     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
467     let sid = HExtlib.unopt sid in
468     (*
469     cgi # set_header 
470       ~cache:`No_cache 
471       ~content_type:"text/xml; charset=\"utf-8\""
472       ();
473     *)
474     let text = cgi#argument_value "body" in
475     (* prerr_endline ("body =\n" ^ text); *)
476     let history = MatitaAuthentication.get_history sid in
477     let parsed_len, new_parsed, new_unparsed, new_status = advance0 sid text in
478     MatitaAuthentication.set_history sid (new_status::history);
479     let txt = output_status new_status in
480     let body = 
481        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\">" ^
482        new_parsed ^ "</parsed>" ^ txt 
483        ^ "</response>"
484     in 
485     (* prerr_endline ("sending advance response:\n" ^ body); *)
486     cgi # set_header 
487       ~cache:`No_cache 
488       ~content_type:"text/xml; charset=\"utf-8\""
489       ();
490     cgi#out_channel#output_string body
491   with
492   | Not_found _ -> 
493     cgi # set_header
494       ~status:`Internal_server_error
495       ~cache:`No_cache 
496       ~content_type:"text/xml; charset=\"utf-8\""
497       ());
498   cgi#out_channel#commit_work()
499 ;;
500
501 let gotoBottom (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
502   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
503   let env = cgi#environment in
504   (try 
505     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
506     let sid = HExtlib.unopt sid in
507     let history = MatitaAuthentication.get_history sid in
508
509     let rec aux parsed_len parsed_txt text =
510       try
511         prerr_endline ("evaluating: " ^ first_line text);
512         let plen,new_parsed,new_unparsed,_new_status = advance0 sid text in
513         aux (parsed_len+plen) (parsed_txt ^ new_parsed) new_unparsed
514       with 
515       | End_of_file -> 
516           let status = MatitaAuthentication.get_status sid in
517           GrafiteTypes.Serializer.serialize 
518             ~baseuri:(NUri.uri_of_string status#baseuri) status;
519           if parsed_len > 0 then 
520             MatitaAuthentication.set_history sid (status::history);
521           parsed_len, parsed_txt
522       | _ -> parsed_len, parsed_txt
523     in
524     (* 
525     cgi # set_header 
526       ~cache:`No_cache 
527       ~content_type:"text/xml; charset=\"utf-8\""
528       ();
529     *)
530     let text = cgi#argument_value "body" in
531     (* prerr_endline ("body =\n" ^ text); *)
532     let parsed_len, new_parsed = aux 0 "" text in
533     let status = MatitaAuthentication.get_status sid in
534     let txt = output_status status in
535     let body = 
536        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\">" ^
537        new_parsed ^ "</parsed>" ^ txt 
538        ^ "</response>"
539     in 
540     (*let body = 
541        "<response><parsed length=\"" ^ (string_of_int parsed_len) ^ "\" />" ^ txt 
542        ^ "</response>"
543     in*) 
544     (* prerr_endline ("sending goto bottom response:\n" ^ body); *)
545     cgi # set_header 
546       ~cache:`No_cache 
547       ~content_type:"text/xml; charset=\"utf-8\""
548       ();
549     cgi#out_channel#output_string body
550    with Not_found -> cgi#set_header ~status:`Internal_server_error 
551       ~cache:`No_cache 
552       ~content_type:"text/xml; charset=\"utf-8\"" ());
553   cgi#out_channel#commit_work() 
554 ;;
555
556 let gotoTop (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
557   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
558   let env = cgi#environment in
559   prerr_endline "executing goto Top";
560   (try 
561     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
562     let sid = HExtlib.unopt sid in
563     (*
564     cgi # set_header 
565       ~cache:`No_cache 
566       ~content_type:"text/xml; charset=\"utf-8\""
567       ();
568     *)
569     let status = MatitaAuthentication.get_status sid in
570     let uid = MatitaAuthentication.user_of_session sid in
571     let baseuri = status#baseuri in
572     let new_status = new MatitaEngine.status (Some uid) baseuri in
573     prerr_endline "gototop prima della time travel";
574     NCicLibrary.time_travel new_status;
575     prerr_endline "gototop dopo della time travel";
576     let new_history = [new_status] in 
577     MatitaAuthentication.set_history sid new_history;
578     MatitaAuthentication.set_status sid new_status;
579     NCicLibrary.time_travel new_status;
580     cgi # set_header 
581       ~cache:`No_cache 
582       ~content_type:"text/xml; charset=\"utf-8\""
583       ();
584     cgi#out_channel#output_string "<response>ok</response>"
585    with _ -> 
586      (cgi#set_header ~status:`Internal_server_error 
587       ~cache:`No_cache 
588       ~content_type:"text/xml; charset=\"utf-8\"" ();
589       cgi#out_channel#output_string "<response>ok</response>"));
590   cgi#out_channel#commit_work() 
591 ;;
592
593 let retract (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
594   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
595   let env = cgi#environment in
596   (try 
597     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
598     let sid = HExtlib.unopt sid in
599     (*
600     cgi # set_header 
601       ~cache:`No_cache 
602       ~content_type:"text/xml; charset=\"utf-8\""
603       ();
604     *)
605     let history = MatitaAuthentication.get_history sid in
606     let new_history,new_status =
607        match history with
608          _::(status::_ as history) ->
609           history, status
610       | [_] -> (prerr_endline "singleton";failwith "retract")
611       | _ -> (prerr_endline "nil"; assert false) in
612     prerr_endline ("prima della time travel");
613     NCicLibrary.time_travel new_status;
614     prerr_endline ("dopo della time travel");
615     MatitaAuthentication.set_history sid new_history;
616     MatitaAuthentication.set_status sid new_status;
617     prerr_endline ("baseuri after retract = " ^ new_status#baseuri);
618     let body = output_status new_status in
619     cgi # set_header 
620       ~cache:`No_cache 
621       ~content_type:"text/xml; charset=\"utf-8\""
622       ();
623     cgi#out_channel#output_string body
624    with _ -> cgi#set_header ~status:`Internal_server_error 
625       ~cache:`No_cache 
626       ~content_type:"text/xml; charset=\"utf-8\"" ());
627   cgi#out_channel#commit_work() 
628 ;;
629
630
631 let viewLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
632   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
633   let env = cgi#environment in
634   
635     let sid = Uuidm.of_string (Netcgi.Cookie.value (env#cookie "session")) in
636     let sid = HExtlib.unopt sid in
637     (*
638     cgi # set_header 
639       ~cache:`No_cache 
640       ~content_type:"text/html; charset=\"utf-8\""
641       ();
642     *)
643     let uid = MatitaAuthentication.user_of_session sid in
644     
645     let ft = MatitaAuthentication.read_ft uid in
646     let html = MatitaFilesystem.html_of_library uid ft in
647     cgi # set_header 
648       ~cache:`No_cache 
649       ~content_type:"text/html; charset=\"utf-8\""
650       ();
651     cgi#out_channel#output_string
652       ((*
653        "<html><head>\n" ^
654        "<title>XML Tree Control</title>\n" ^
655        "<link href=\"treeview/xmlTree.css\" type=\"text/css\" rel=\"stylesheet\">\n" ^
656        "<script src=\"treeview/xmlTree.js\" type=\"text/javascript\"></script>\n" ^
657        "<body>\n" ^ *)
658        html (* ^ "\n</body></html>" *) );
659     
660     let files,anomalies = MatitaFilesystem.stat_user uid in
661     let changed = HExtlib.filter_map 
662       (fun (n,fl) -> if (List.mem MatitaFilesystem.Modified fl) then Some n else None) files
663     in
664     let changed = String.concat "\n" changed in
665     let anomalies = String.concat "\n" anomalies in
666     prerr_endline ("Changed:\n" ^ changed ^ "\n\nAnomalies:\n" ^ anomalies);
667   cgi#out_channel#commit_work()
668   
669 ;;
670
671 let resetLib (cgi : Netcgi1_compat.Netcgi_types.cgi_activation) =
672   let cgi = Netcgi1_compat.Netcgi_types.of_compat_activation cgi in
673   MatitaAuthentication.reset ();
674     cgi # set_header 
675       ~cache:`No_cache 
676       ~content_type:"text/html; charset=\"utf-8\""
677       ();
678     
679     cgi#out_channel#output_string
680       ("<html><head>\n" ^
681        "<title>Matitaweb Reset</title>\n" ^
682        "<body><H1>Reset completed</H1></body></html>");
683     cgi#out_channel#commit_work()
684
685 open Netcgi1_compat.Netcgi_types;;
686
687 (**********************************************************************)
688 (* Create the webserver                                               *)
689 (**********************************************************************)
690
691
692 let start() =
693   let (opt_list, cmdline_cfg) = Netplex_main.args() in
694
695   let use_mt = ref true in
696
697   let opt_list' =
698     [ "-mt", Arg.Set use_mt,
699       "  Use multi-threading instead of multi-processing"
700     ] @ opt_list in
701
702   Arg.parse 
703     opt_list'
704     (fun s -> raise (Arg.Bad ("Don't know what to do with: " ^ s)))
705     "usage: netplex [options]";
706   let parallelizer = 
707     if !use_mt then
708       Netplex_mt.mt()     (* multi-threading *)
709     else
710       Netplex_mp.mp() in  (* multi-processing *)
711 (*
712   let adder =
713     { Nethttpd_services.dyn_handler = (fun _ -> process1);
714       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
715       dyn_uri = None;                 (* not needed *)
716       dyn_translator = (fun _ -> ""); (* not needed *)
717       dyn_accept_all_conditionals = false;
718     } in
719 *)
720   let do_advance =
721     { Nethttpd_services.dyn_handler = (fun _ -> advance);
722       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
723       dyn_uri = None;                 (* not needed *)
724       dyn_translator = (fun _ -> ""); (* not needed *)
725       dyn_accept_all_conditionals = false;
726     } in
727   let do_retract =
728     { Nethttpd_services.dyn_handler = (fun _ -> retract);
729       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
730       dyn_uri = None;                 (* not needed *)
731       dyn_translator = (fun _ -> ""); (* not needed *)
732       dyn_accept_all_conditionals = false;
733     } in
734   let goto_bottom =
735     { Nethttpd_services.dyn_handler = (fun _ -> gotoBottom);
736       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
737       dyn_uri = None;                 (* not needed *)
738       dyn_translator = (fun _ -> ""); (* not needed *)
739       dyn_accept_all_conditionals = false;
740     } in
741   let goto_top =
742     { Nethttpd_services.dyn_handler = (fun _ -> gotoTop);
743       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
744       dyn_uri = None;                 (* not needed *)
745       dyn_translator = (fun _ -> ""); (* not needed *)
746       dyn_accept_all_conditionals = false;
747     } in
748   let retrieve =
749     { Nethttpd_services.dyn_handler = (fun _ -> retrieve);
750       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
751       dyn_uri = None;                 (* not needed *)
752       dyn_translator = (fun _ -> ""); (* not needed *)
753       dyn_accept_all_conditionals = false;
754     } in
755   let do_register =
756     { Nethttpd_services.dyn_handler = (fun _ -> register);
757       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
758       dyn_uri = None;                 (* not needed *)
759       dyn_translator = (fun _ -> ""); (* not needed *)
760       dyn_accept_all_conditionals = false;
761     } in
762   let do_login =
763     { Nethttpd_services.dyn_handler = (fun _ -> login);
764       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
765       dyn_uri = None;                 (* not needed *)
766       dyn_translator = (fun _ -> ""); (* not needed *)
767       dyn_accept_all_conditionals = false;
768     } in
769   let do_logout =
770     { Nethttpd_services.dyn_handler = (fun _ -> logout);
771       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
772       dyn_uri = None;                 (* not needed *)
773       dyn_translator = (fun _ -> ""); (* not needed *)
774       dyn_accept_all_conditionals = false;
775     } in 
776   let do_viewlib =
777     { Nethttpd_services.dyn_handler = (fun _ -> viewLib);
778       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
779       dyn_uri = None;                 (* not needed *)
780       dyn_translator = (fun _ -> ""); (* not needed *)
781       dyn_accept_all_conditionals = false;
782     } in 
783   let do_resetlib =
784     { Nethttpd_services.dyn_handler = (fun _ -> resetLib);
785       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
786       dyn_uri = None;                 (* not needed *)
787       dyn_translator = (fun _ -> ""); (* not needed *)
788       dyn_accept_all_conditionals = false;
789     } in 
790   let do_save =
791     { Nethttpd_services.dyn_handler = (fun _ -> save);
792       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
793       dyn_uri = None;                 (* not needed *)
794       dyn_translator = (fun _ -> ""); (* not needed *)
795       dyn_accept_all_conditionals = false;
796     } in 
797   let do_commit =
798     { Nethttpd_services.dyn_handler = (fun _ -> initiate_commit);
799       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
800       dyn_uri = None;                 (* not needed *)
801       dyn_translator = (fun _ -> ""); (* not needed *)
802       dyn_accept_all_conditionals = false;
803     } in 
804   let do_update =
805     { Nethttpd_services.dyn_handler = (fun _ -> svn_update);
806       dyn_activation = Nethttpd_services.std_activation `Std_activation_buffered;
807       dyn_uri = None;                 (* not needed *)
808       dyn_translator = (fun _ -> ""); (* not needed *)
809       dyn_accept_all_conditionals = false;
810     } in 
811   
812   
813   let nethttpd_factory = 
814     Nethttpd_plex.nethttpd_factory
815       ~handlers:[ "advance", do_advance
816                 ; "retract", do_retract
817                 ; "bottom", goto_bottom
818                 ; "top", goto_top
819                 ; "open", retrieve 
820                 ; "register", do_register
821                 ; "login", do_login 
822                 ; "logout", do_logout 
823                 ; "reset", do_resetlib
824                 ; "viewlib", do_viewlib
825                 ; "save", do_save
826                 ; "commit", do_commit
827                 ; "update", do_update]
828       () in
829   MatitaInit.initialize_all ();
830   MatitaAuthentication.deserialize ();
831   Netplex_main.startup
832     parallelizer
833     Netplex_log.logger_factories   (* allow all built-in logging styles *)
834     Netplex_workload.workload_manager_factories (* ... all ways of workload management *)
835     [ nethttpd_factory ]           (* make this nethttpd available *)
836     cmdline_cfg
837 ;;
838
839 Sys.set_signal Sys.sigpipe Sys.Signal_ignore;
840 start();;