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