0f90e1961c5762c6f2d01671a230751e19aa4e23
[cocanwiki.git] / scripts / upload_file.ml
1 (* COCANWIKI scripts.
2  * Written by Richard W.M. Jones <rich@merjis.com>.
3  * Copyright (C) 2004 Merjis Ltd.
4  * $Id: upload_file.ml,v 1.2 2004/09/07 13:40:10 rich Exp $
5  *)
6
7 open Apache
8 open Registry
9 open Cgi
10 open Printf
11
12 open ExtString
13
14 open Merjisforwiki
15
16 open Cocanwiki
17 open Cocanwiki_template
18 open Cocanwiki_ok
19 open Cocanwiki_emailnotify
20
21 let is_ws_re = Pcre.regexp "^\\s*$"
22 let is_whitespace str = Pcre.pmatch ~rex:is_ws_re str
23
24 (* Valid file names. *)
25 let file_ok_re = Pcre.regexp "^[a-z0-9][-._a-z0-9]*$"
26
27 let run r (q : cgi) (dbh : Dbi.connection) (hostid, hostname, _) _ =
28   let name = q#param "name" in
29   let title = q#param "title" in
30
31   (* See if there was an upload. *)
32   let file =
33     try
34       let upload = q#upload "file" in
35       upload.upload_value
36     with
37         Not_found ->
38           error ~title:"No file" ~back_button:true
39             q "No file was uploaded.";
40           raise CgiExit in
41
42   (* Check the name is valid. *)
43   if not (Pcre.pmatch ~rex:file_ok_re name) then (
44     error ~title:"Bad File Name" ~back_button:true
45       q ("The File Name must contain only lowercase English letters, " ^
46          "numbers, dots, dashes and underscore.");
47     raise CgiExit
48   );
49
50   (* Identify the MIME type from the extension. *)
51   let mime_type = mime_type_of_filename name in
52
53   let title = if is_whitespace title then `Null else `String title in
54
55   (* Put the file into the database. *)
56   let sth =
57     dbh#prepare_cached
58       "insert into files (hostid, name, content, title, mime_type)
59        values (?, ?, ?, ?, ?)" in
60   sth#execute [`Int hostid; `String name; `Binary file; title;
61                `String mime_type];
62
63   dbh#commit ();
64
65   (* Email notify. *)
66   let subject = "File " ^ name ^ " has been uploaded." in
67   let body = fun () ->
68     "Page: http://" ^ hostname ^ "/_files" in
69
70   email_notify ~body ~subject dbh hostid;
71
72   let buttons = [ ok_button "/_files" ] in
73   ok ~title:"File uploaded" ~buttons
74     q "File was uploaded successfully."
75
76 let () =
77   register_script run