2 package IkiWiki::Plugin::attachment;
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");
26 allowed_attachments => {
28 example => "virusfree() and mimetype(image/*) and maxsize(50kb)",
29 description => "enhanced PageSpec specifying what attachments are allowed",
30 link => "ikiwiki/PageSpec/attachment",
36 example => "clamdscan -",
37 description => "virus checker program (reads STDIN, returns nonzero if virus found)",
43 sub check_canattach ($$;$) {
45 my $dest=shift; # where it's going to be put, under the srcdir
46 my $file=shift; # the path to the attachment currently
48 # Don't allow an attachment to be uploaded with the same name as an
50 if (exists $IkiWiki::pagesources{$dest} &&
51 $IkiWiki::pagesources{$dest} ne $dest) {
52 error(sprintf(gettext("there is already a page named %s"), $dest));
55 # Use a special pagespec to test that the attachment is valid.
57 if (defined $config{allowed_attachments} &&
58 length $config{allowed_attachments}) {
59 $allowed=pagespec_match($dest,
60 $config{allowed_attachments},
62 user => $session->param("name"),
63 ip => $session->remote_addr(),
68 error(gettext("prohibited by allowed_attachments")." ($allowed)");
76 $config{cgi_disable_uploads}=0;
79 sub formbuilder_setup (@) {
81 my $form=$params{form};
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" />');
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
102 foreach my $file (@jsfiles) {
103 $js.='<script src="'.urlto("ikiwiki/$file.js", $params{page}).
104 '" type="text/javascript" charset="utf-8"></script>'."\n";
106 $form->tmpl_param("javascript" => $js);
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");
116 $form->tmpl_param("attachments-class" => "toggleable-open");
119 # Save attachments in holding area before previewing and
121 if ($form->submitted eq "Preview" ||
122 $form->submitted eq "Save Page") {
123 attachments_save($form, $params{session});
128 sub formbuilder (@) {
130 my $form=$params{form};
133 return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
135 my $filename=Encode::decode_utf8(scalar $q->param('attachment'));
136 my $handle=$q->upload('attachment');
138 if (defined $filename && length $filename) {
139 attachment_store($filename, $handle, $form, $q, $params{session});
142 if ($form->submitted eq "Save Page") {
143 attachments_save($form, $params{session});
146 if ($form->submitted eq "Insert Links") {
147 my $page=quotemeta(Encode::decode_utf8(scalar $q->param("page")));
149 foreach my $f (@{$q->param_fetch("attachment_select")}) {
150 $f=Encode::decode_utf8($f);
152 if (IkiWiki::isinlinableimage($f) &&
153 IkiWiki::Plugin::img->can("import")) {
154 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
161 $form->field(name => 'editcontent',
162 value => $form->field('editcontent')."\n\n".$add,
163 force => 1) if length $add;
166 # Generate the attachment list only after having added any new
168 $form->tmpl_param("attachment_list" => [attachment_list(scalar $form->field('page'))]);
171 sub attachment_holding_location {
172 my $page=attachment_location(shift);
174 my $dir=$config{wikistatedir}."/attachments/".
175 IkiWiki::possibly_foolish_untaint(linkpage($page));
180 sub is_held_attachment {
181 my $attachment=shift;
183 my $f=attachment_holding_location($attachment);
192 # Stores the attachment in a holding area, not yet in the wiki proper.
193 sub attachment_store {
201 if (defined $handle) {
202 # This is what works in CGI.pm 4.09+: $q->tmpFileName($q->upload('attachment'))
203 $tempfile=$q->tmpFileName($handle);
205 if (! defined $tempfile || ! length $tempfile) {
206 # This is what is *documented* in CGI.pm 4.09: $q->tmpFileName($q->param('attachment'))
207 $tempfile=$q->tmpFileName($filename);
209 if (! defined $tempfile || ! length $tempfile) {
210 # perl 5.8 needs an alternative, awful method
211 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
212 foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
213 $tempfile=$q->tmpFileName(\$key);
214 last if defined $tempfile && length $tempfile;
218 if (! defined $tempfile || ! length $tempfile) {
219 error("CGI::tmpFileName failed to return the uploaded file name");
222 $filename=IkiWiki::basename($filename);
223 $filename=~s/.*\\+(.+)/$1/; # hello, windows
224 $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
225 my $dest=attachment_holding_location($form->field('page'));
227 # Check that the user is allowed to edit the attachment.
229 linkpage(IkiWiki::possibly_foolish_untaint(
230 attachment_location($form->field('page')))).
233 if (IkiWiki::file_pruned($final_filename)) {
234 error(gettext("bad attachment filename"));
236 IkiWiki::check_canedit($final_filename, $q, $session);
237 # And that the attachment itself is acceptable.
238 check_canattach($session, $final_filename, $tempfile);
241 # save error in case called functions clobber $@
243 json_response($q, $form, $dest."/".$filename, $error);
247 # Move the attachment into holding directory.
248 # Try to use a fast rename; fall back to copying.
249 IkiWiki::prep_writefile($filename, $dest);
250 unlink($dest."/".$filename);
251 if (rename($tempfile, $dest."/".$filename)) {
252 # The temp file has tight permissions; loosen up.
253 chmod(0666 & ~umask, $dest."/".$filename);
256 my $fh=$q->upload('attachment');
257 if (! defined $fh || ! ref $fh) {
258 # needed by old CGI versions
259 $fh=$q->param('attachment');
260 if (! defined $fh || ! ref $fh) {
261 # even that doesn't always work,
262 # fall back to opening the tempfile
264 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
268 require IkiWiki::Render;
269 writefile($filename, $dest, undef, 1, sub {
270 IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
274 json_response($q, $form, $dest."/".$filename, stored_msg());
277 # Save all stored attachments for a page.
278 sub attachments_save {
282 # Move attachments out of holding directory.
284 my $dir=attachment_holding_location($form->field('page'));
285 foreach my $filename (glob("$dir/*")) {
286 $filename=Encode::decode_utf8($filename);
287 next unless -f $filename;
288 my $destdir=linkpage(IkiWiki::possibly_foolish_untaint(
289 attachment_location($form->field('page'))));
290 my $absdestdir=$config{srcdir}."/".$destdir;
291 my $destfile=IkiWiki::basename($filename);
292 my $dest=$absdestdir.$destfile;
294 IkiWiki::prep_writefile($destfile, $absdestdir);
295 rename($filename, $dest);
296 push @attachments, $destdir.$destfile;
298 return unless @attachments;
299 require IkiWiki::Render;
300 IkiWiki::prune($dir, $config{wikistatedir}."/attachments");
302 # Check the attachments in and trigger a wiki refresh.
304 IkiWiki::rcs_add($_) foreach @attachments;
305 IkiWiki::disable_commit_hook();
306 IkiWiki::rcs_commit_staged(
307 message => gettext("attachment upload"),
310 IkiWiki::enable_commit_hook();
311 IkiWiki::rcs_update();
314 IkiWiki::saveindex();
317 sub attachment_location ($) {
320 # Put the attachment in a subdir of the page it's attached
321 # to, unless that page is the "index" page.
322 return "" if $page eq 'index';
323 $page.="/" if length $page;
328 sub attachment_list ($) {
330 my $loc=attachment_location($page);
339 size => IkiWiki::Plugin::filecheck::humansize($size),
344 # attachments already in the wiki
346 foreach my $f (values %pagesources) {
347 if (! defined pagetype($f) &&
348 $f=~m/^\Q$loc\E[^\/]+$/) {
350 $std->($f, $IkiWiki::pagemtime{$f}, displaytime($IkiWiki::pagemtime{$f}), (stat($f))[7]),
351 link => htmllink($page, $page, $f, noimageinline => 1),
356 # attachments in holding directory
357 my $dir=attachment_holding_location($page);
358 my $heldmsg=gettext("this attachment is not yet saved");
359 foreach my $file (glob("$dir/*")) {
360 $file=Encode::decode_utf8($file);
361 next unless -f $file;
362 my $base=IkiWiki::basename($file);
365 $std->($f, (stat($file))[9]*2, stored_msg(), (stat(_))[7]),
370 # Sort newer attachments to the end of the list.
371 return sort { $a->{mtime_raw} <=> $b->{mtime_raw} || $a->{link} cmp $b->{link} }
376 gettext("just uploaded");
379 sub json_response ($$$$) {
383 my $stored_msg=shift;
385 if (! defined $form->submitted ||
386 $form->submitted ne "Upload Attachment") {
389 print "Content-type: text/html\n\n";
390 my $size=-s $filename;
393 name => IkiWiki::basename($filename),
395 humansize => IkiWiki::Plugin::filecheck::humansize($size),
396 stored_msg => $stored_msg,