WIP
[ikiwiki.git] / IkiWiki / Plugin / attachment.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::attachment;
3
4 use warnings;
5 use strict;
6 use IkiWiki 3.00;
7
8 sub import {
9         add_underlay("javascript");
10         hook(type => "getsetup", id => "attachment", call => \&getsetup);
11         hook(type => "checkconfig", id => "attachment", call => \&checkconfig);
12         hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
13         hook(type => "formbuilder", id => "attachment", call => \&formbuilder, last => 1);
14         IkiWiki::loadplugin("filecheck");
15 }
16
17 sub getsetup () {
18         return
19                 plugin => {
20                         safe => 1,
21                         rebuild => 0,
22                         section => "web",
23                 },
24                 allowed_attachments => {
25                         type => "pagespec",
26                         example => "virusfree() and mimetype(image/*) and maxsize(50kb)",
27                         description => "enhanced PageSpec specifying what attachments are allowed",
28                         link => "ikiwiki/PageSpec/attachment",
29                         safe => 1,
30                         rebuild => 0,
31                 },
32                 virus_checker => {
33                         type => "string",
34                         example => "clamdscan -",
35                         description => "virus checker program (reads STDIN, returns nonzero if virus found)",
36                         safe => 0, # executed
37                         rebuild => 0,
38                 },
39 }
40
41 sub check_canattach ($$;$) {
42         my $session=shift;
43         my $dest=shift; # where it's going to be put, under the srcdir
44         my $file=shift; # the path to the attachment currently
45
46         # Don't allow an attachment to be uploaded with the same name as an
47         # existing page.
48         if (exists $IkiWiki::pagesources{$dest} &&
49             $IkiWiki::pagesources{$dest} ne $dest) {
50                 error(sprintf(gettext("there is already a page named %s"), $dest));
51         }
52
53         # Use a special pagespec to test that the attachment is valid.
54         my $allowed=1;
55         if (defined $config{allowed_attachments} &&
56             length $config{allowed_attachments}) {
57                 $allowed=pagespec_match($dest,
58                         $config{allowed_attachments},
59                         file => $file,
60                         user => $session->param("name"),
61                         ip => $session->remote_addr(),
62                 );
63         }
64
65         if (! $allowed) {
66                 error(gettext("prohibited by allowed_attachments")." ($allowed)");
67         }
68         else {
69                 return 1;
70         }
71 }
72
73 sub checkconfig () {
74         $config{cgi_disable_uploads}=0;
75 }
76
77 sub formbuilder_setup (@) {
78         my %params=@_;
79         my $form=$params{form};
80         my $q=$params{cgi};
81
82         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
83             $form->field("do") eq "create")) {
84                 # Add attachment field, set type to multipart.
85                 $form->enctype(&CGI::MULTIPART);
86                 $form->field(name => 'attachment', type => 'file');
87                 # These buttons are not put in the usual place, so
88                 # are not added to the normal formbuilder button list.
89                 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
90                 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
91
92                 # Add the toggle javascript; the attachments interface uses
93                 # it to toggle visibility.
94                 require IkiWiki::Plugin::toggle;
95                 $form->tmpl_param("javascript" => IkiWiki::Plugin::toggle::include_javascript($params{page}));
96                 # Start with the attachments interface toggled invisible,
97                 # but if it was used, keep it open.
98                 if ($form->submitted ne "Upload Attachment" &&
99                     (! defined $q->param("attachment_select") ||
100                     ! length $q->param("attachment_select"))) {
101                         $form->tmpl_param("attachments-class" => "toggleable");
102                 }
103                 else {
104                         $form->tmpl_param("attachments-class" => "toggleable-open");
105                 }
106                 
107                 # Save attachments in holding area before previewing so
108                 # they can be seen in the preview.
109                 if ($form->submitted eq "Preview") {
110                         attachments_save($form, $params{session});
111                 }
112         }
113 }
114
115 sub formbuilder (@) {
116         my %params=@_;
117         my $form=$params{form};
118         my $q=$params{cgi};
119
120         return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
121
122         my $filename=Encode::decode_utf8($q->param('attachments'));
123         if (defined $filename && length $filename) {
124                 attachment_store($filename, $form, $q, $params{session});
125         }
126
127         if ($form->submitted eq "Save Page") {
128                 attachments_save($form, $params{session});
129         }
130
131         if ($form->submitted eq "Insert Links") {
132                 my $page=quotemeta(Encode::decode_utf8($q->param("page")));
133                 my $add="";
134                 foreach my $f ($q->param("attachment_select")) {
135                         $f=Encode::decode_utf8($f);
136                         $f=~s/^$page\///;
137                         if (IkiWiki::isinlinableimage($f) &&
138                             UNIVERSAL::can("IkiWiki::Plugin::img", "import")) {
139                                 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
140                         }
141                         else {
142                                 $add.="[[$f]]";
143                         }
144                         $add.="\n";
145                 }
146                 $form->field(name => 'editcontent',
147                         value => $form->field('editcontent')."\n\n".$add,
148                         force => 1) if length $add;
149         }
150         
151         # Generate the attachment list only after having added any new
152         # attachments.
153         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
154 }
155
156 sub attachment_holding_location {
157         my $page=attachment_location(shift);
158
159         my $dir=$config{wikistatedir}."/attachments/".
160                 IkiWiki::possibly_foolish_untaint(linkpage($page));
161         $dir=~s/\/$//;
162         return $dir;
163 }
164
165 sub is_held_attachment {
166         my $attachment=shift;
167
168         my $f=attachment_holding_location($attachment);
169         if (-f $f) {
170                 return $f
171         }
172         else {
173                 return undef;
174         }
175 }
176
177 # Stores the attachment in a holding area, not yet in the wiki proper.
178 sub attachment_store {
179         my $filename=shift;
180         my $form=shift;
181         my $q=shift;
182         my $session=shift;
183         
184         # This is an (apparently undocumented) way to get the name
185         # of the temp file that CGI writes the upload to.
186         my $tempfile=$q->tmpFileName($filename);
187         if (! defined $tempfile || ! length $tempfile) {
188                 # perl 5.8 needs an alternative, awful method
189                 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
190                         foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
191                                 $tempfile=$q->tmpFileName(\$key);
192                                 last if defined $tempfile && length $tempfile;
193                         }
194                 }
195                 if (! defined $tempfile || ! length $tempfile) {
196                         error("CGI::tmpFileName failed to return the uploaded file name");
197                 }
198         }
199
200         $filename=IkiWiki::basename($filename);
201         $filename=~s/.*\\+(.+)/$1/; # hello, windows
202         $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
203         
204         # Check that the user is allowed to edit the attachment.
205         my $final_filename=
206                 linkpage(IkiWiki::possibly_foolish_untaint(
207                         attachment_location($form->field('page')))).
208                 $filename;
209         if (IkiWiki::file_pruned($final_filename)) {
210                 error(gettext("bad attachment filename"));
211         }
212         IkiWiki::check_canedit($final_filename, $q, $session);
213         # And that the attachment itself is acceptable.
214         check_canattach($session, $final_filename, $tempfile);
215
216         # Move the attachment into holding directory.
217         # Try to use a fast rename; fall back to copying.
218         my $dest=attachment_holding_location($form->field('page'));
219         IkiWiki::prep_writefile($filename, $dest);
220         unlink($dest."/".$filename);
221         if (rename($tempfile, $dest."/".$filename)) {
222                 # The temp file has tight permissions; loosen up.
223                 chmod(0666 & ~umask, $dest."/".$filename);
224         }
225         else {
226                 my $fh=$q->upload('attachment');
227                 if (! defined $fh || ! ref $fh) {
228                         # needed by old CGI versions
229                         $fh=$q->param('attachment');
230                         if (! defined $fh || ! ref $fh) {
231                                 # even that doesn't always work,
232                                 # fall back to opening the tempfile
233                                 $fh=undef;
234                                 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
235                         }
236                 }
237                 binmode($fh);
238                 require IkiWiki::Render; 
239                 writefile($filename, $dest, undef, 1, sub {
240                         IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
241                 });
242         }
243         
244         # Return JSON response for the jquery file upload widget.
245         eval q{use JSON};
246         error $@ if $@;
247         print "Content-type: application/json\n\n";
248         my $size=-s $dest."/".$filename;
249         print to_json([
250                 {
251                         name => $filename,
252                         size => $size,
253                         humansize => IkiWiki::Plugin::filecheck::humansize($size),
254                         stored_msg => stored_msg(),
255                         
256                 }
257         ]);
258         exit 0;
259 }
260
261 # Save all stored attachments for a page.
262 sub attachments_save {
263         my $form=shift;
264         my $session=shift;
265
266         # Move attachments out of holding directory.
267         my @attachments;
268         my $dir=attachment_holding_location($form->field('page'));
269         foreach my $filename (glob("$dir/*")) {
270                 next unless -f $filename;
271                 my $dest=$config{srcdir}."/".
272                         linkpage(IkiWiki::possibly_foolish_untaint(
273                                 attachment_location($form->field('page')))).
274                         IkiWiki::basename($filename);
275                 unlink($dest);
276                 rename($filename, $dest);
277                 push @attachments, $dest;
278         }
279         return unless @attachments;
280         require IkiWiki::Render;
281         IkiWiki::prune($dir);
282
283         # Check the attachments in and trigger a wiki refresh.
284         if ($config{rcs}) {
285                 IkiWiki::rcs_add($_) foreach @attachments;
286                 IkiWiki::disable_commit_hook();
287                 IkiWiki::rcs_commit_staged(
288                         message => gettext("attachment upload"),
289                         session => $session,
290                 );
291                 IkiWiki::enable_commit_hook();
292                 IkiWiki::rcs_update();
293         }
294         IkiWiki::refresh();
295         IkiWiki::saveindex();
296 }
297
298 sub attachment_location ($) {
299         my $page=shift;
300         
301         # Put the attachment in a subdir of the page it's attached
302         # to, unless that page is an "index" page.
303         $page=~s/(^|\/)index//;
304         $page.="/" if length $page;
305         
306         return $page;
307 }
308
309 sub attachment_list ($) {
310         my $page=shift;
311         my $loc=attachment_location($page);
312
313         my $std=sub {
314                 my $file=shift;
315                 my $mtime=shift;
316                 my $date=shift;
317                 my $size=shift;
318
319                 name => $file,
320                 size => IkiWiki::Plugin::filecheck::humansize($size),
321                 mtime => $date,
322                 mtime_raw => $mtime,
323         };
324
325         # attachments already in the wiki
326         my %attachments;
327         foreach my $f (values %pagesources) {
328                 if (! defined pagetype($f) &&
329                     $f=~m/^\Q$loc\E[^\/]+$/) {
330                         $attachments{$f}={
331                                 $std->($f, $IkiWiki::pagemtime{$f}, displaytime($IkiWiki::pagemtime{$f}), (stat($f))[7]),
332                                 link => htmllink($page, $page, $f, noimageinline => 1),
333                         };
334                 }
335         }
336         
337         # attachments in holding directory
338         my $dir=attachment_holding_location($page);
339         my $heldmsg=gettext("this attachment is not yet saved");
340         foreach my $file (glob("$dir/*")) {
341                 next unless -f $file;
342                 my $base=IkiWiki::basename($file);
343                 my $f=$loc.$base;
344                 $attachments{$f}={
345                         $std->($f, (stat($file))[9], stored_msg(), (stat(_))[7]),
346                         link => $base,
347                 }
348         }
349
350         # Sort newer attachments to the end of the list.
351         return sort { $a->{mtime_raw} <=> $b->{mtime_raw} || $a->{link} cmp $b->{link} }
352                 values %attachments;
353 }
354
355 sub stored_msg {
356         gettext("just uploaded");
357 }
358
359 1