cust_attachment improvement, RT#4964 and #6225
[freeside.git] / httemplate / edit / process / cust_main_attach.cgi
1 %if ($error) {
2 %  $cgi->param('error', $error);
3 <% $cgi->redirect(popurl(2). 'cust_main_attach.cgi?'. $cgi->query_string ) %>
4 %} else {
5 % my $act = 'added';
6 % $act = 'updated' if ($attachnum);
7 % $act = 'purged' if($attachnum and $purge);
8 % $act = 'undeleted' if($attachnum and $undelete);
9 % $act = 'deleted' if($attachnum and $delete);
10 <% header('Attachment ' . $act ) %>
11     <SCRIPT TYPE="text/javascript">
12       window.top.location.reload();
13     </SCRIPT>
14     </BODY></HTML>
15 % }
16 <%init>
17
18 my $error;
19 $cgi->param('custnum') =~ /^(\d+)$/
20   or die "Illegal custnum: ". $cgi->param('custnum');
21 my $custnum = $1;
22
23 $cgi->param('attachnum') =~ /^(\d*)$/
24   or die "Illegal attachnum: ". $cgi->param('attachnum');
25 my $attachnum = $1;
26
27 my $curuser = $FS::CurrentUser::CurrentUser;
28 my $otaker = $curuser->name;
29 $otaker = $curuser->username if ($otaker eq "User, Legacy");
30
31 my $delete = $cgi->param('delete');
32 my $undelete = $cgi->param('undelete');
33 my $purge = $cgi->param('purge');
34
35 my $new = new FS::cust_attachment ( {
36   attachnum => $attachnum,
37   custnum   => $custnum,
38   _date     => time,
39   otaker    => $otaker,
40   disabled  => '',
41 });
42 my $old;
43
44 if($attachnum) {
45   $old = qsearchs('cust_attachment', { attachnum => $attachnum });
46   if(!$old) {
47     $error = "Attachnum '$attachnum' not found";
48   }
49   elsif($purge) { # do nothing
50   }
51   else {
52     map { $new->$_($old->$_) } 
53       ('_date', 'otaker', 'body', 'disabled');
54     $new->filename($cgi->param('filename') || $old->filename);
55     $new->mime_type($cgi->param('mime_type') || $old->mime_type);
56     $new->title($cgi->param('title'));
57     if($delete and not $old->disabled) {
58       $new->disabled(time);
59     }
60     if($undelete and $old->disabled) {
61       $new->disabled('');
62     }
63   }
64 }
65 else { # This is a new attachment, so require a file.
66
67   my $filename = $cgi->param('file');
68   if($filename) {
69     $new->filename($filename);
70     $new->mime_type($cgi->uploadInfo($filename)->{'Content-Type'});
71     $new->title($cgi->param('title'));
72     
73     local $/;
74     my $fh = $cgi->upload('file');
75     $new->body(<$fh>);
76   }
77   else {
78     $error = 'No file uploaded';
79   }
80 }
81 my $action = 'Add';
82 $action = 'Edit' if $attachnum;
83 $action = 'Delete' if $attachnum and $delete;
84 $action = 'Undelete' if $attachnum and $undelete;
85 $action = 'Purge' if $attachnum and $purge;
86
87 $error = 'access denied' unless $curuser->access_right($action . ' attachment');
88
89 if(!$error) {
90   if($old and $old->disabled and $purge) {
91     $error = $old->delete;
92   }
93   elsif($old) {
94     $error = $new->replace($old);
95   }
96   else {
97     $error = $new->insert;
98   }
99 }
100
101 </%init>