Logging in and logging out.
[cocanwiki.git] / scripts / cocanwiki_diff.ml
1 (* COCANWIKI scripts.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: cocanwiki_diff.ml,v 1.2 2004/09/07 14:58:34 rich Exp $
5  *)
6
7 open Apache
8 open Registry
9 open Cgi
10 open Printf
11
12 open Cocanwiki_files
13
14 (* Convenience code for generating diffs between versions.  See diff.ml
15  * and edit.ml which both use this code.
16  *)
17 let page_for_diff css sections =
18   (String.concat ""
19      (List.map (fun (sectionname, content) ->
20                   "HEADING: " ^ sectionname ^ "\n\n" ^
21                   content ^ "\n\n") sections)) ^
22   "CSS:\n\n" ^ css
23
24 let diff_cmd old_page new_page =
25   let new_filename = output_tempfile new_page in
26   let old_filename = output_tempfile old_page in
27
28   let cmd = sprintf "diff -u %s %s ||:" old_filename new_filename in
29   let diff = pget cmd in
30
31   let diff =
32     match diff with
33         _ :: _ :: diff -> diff
34       | diff -> diff in
35
36   unlink new_filename; unlink old_filename;
37   String.concat "\n" diff
38
39 let get_version_for_diff (dbh : Dbi.connection) version =
40   if version = 0 then "" else (
41     let sth = dbh#prepare_cached "select coalesce (css, '') as css
42                                     from pages where id = ?" in
43     sth#execute [`Int version];
44
45     let css = sth#fetch1string () in
46
47     let sth = dbh#prepare_cached "select sectionname, content
48                                     from contents where pageid = ?
49                                    order by ordering" in
50     sth#execute [`Int version];
51
52     let sections =
53       sth#map (function
54                    [`String sectionname; `String content] ->
55                      sectionname, content
56                  | _ -> assert false) in
57     let page = page_for_diff css sections in
58
59     page
60   )
61
62 let get_diff (dbh : Dbi.connection) hostid page ?old_version ~version () =
63   let old_version =
64     match old_version with
65       | Some version -> version
66       | None ->
67           let sth = dbh#prepare_cached "select id from pages
68                                          where hostid = ?
69                                            and url_deleted = ? and id < ?
70                                          order by 1 desc limit 1" in
71           sth#execute [`Int hostid; `String page; `Int version];
72
73           try sth#fetch1int ()
74           with Not_found -> 0 in
75
76   (* Get the two versions. *)
77   let new_page = get_version_for_diff dbh version in
78   let old_page = get_version_for_diff dbh old_version in
79
80   (* Compute the diff of the two versions. *)
81   let diff = diff_cmd old_page new_page in
82   diff, old_version