Removed dependency on imported merjislib.
[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.3 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 ExtString
13
14 open Cocanwiki
15 open Cocanwiki_template
16 open Cocanwiki_ok
17 open Cocanwiki_emailnotify
18 open Cocanwiki_images
19
20 let is_ws_re = Pcre.regexp "^\\s*$"
21 let is_whitespace str = Pcre.pmatch ~rex:is_ws_re str
22
23 (* Valid file names. *)
24 let file_ok_re = Pcre.regexp "^[a-z0-9][-._a-z0-9]*$"
25
26 let run r (q : cgi) (dbh : Dbi.connection) (hostid, hostname, _) _ =
27   let name = q#param "name" in
28   let title = q#param "title" in
29
30   (* See if there was an upload. *)
31   let file =
32     try
33       let upload = q#upload "file" in
34       upload.upload_value
35     with
36         Not_found ->
37           error ~title:"No file" ~back_button:true
38             q "No file was uploaded.";
39           raise CgiExit in
40
41   (* Check the name is valid. *)
42   if not (Pcre.pmatch ~rex:file_ok_re name) then (
43     error ~title:"Bad File Name" ~back_button:true
44       q ("The File Name must contain only lowercase English letters, " ^
45          "numbers, dots, dashes and underscore.");
46     raise CgiExit
47   );
48
49   (* Identify the MIME type from the extension. *)
50   let mime_type = mime_type_of_filename name in
51
52   let title = if is_whitespace title then `Null else `String title in
53
54   (* Put the file into the database. *)
55   let sth =
56     dbh#prepare_cached
57       "insert into files (hostid, name, content, title, mime_type)
58        values (?, ?, ?, ?, ?)" in
59   sth#execute [`Int hostid; `String name; `Binary file; title;
60                `String mime_type];
61
62   dbh#commit ();
63
64   (* Email notify. *)
65   let subject = "File " ^ name ^ " has been uploaded." in
66   let body = fun () ->
67     "Page: http://" ^ hostname ^ "/_files" in
68
69   email_notify ~body ~subject dbh hostid;
70
71   let buttons = [ ok_button "/_files" ] in
72   ok ~title:"File uploaded" ~buttons
73     q "File was uploaded successfully."
74
75 let () =
76   register_script run