2 package IkiWiki::Plugin::attachment;
9 add_underlay("javascript");
10 add_underlay("attachment");
11 hook(type => "getsetup", id => "attachment", call => \&getsetup);
12 hook(type => "checkconfig", id => "attachment", call => \&checkconfig);
13 hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
14 hook(type => "formbuilder", id => "attachment", call => \&formbuilder, last => 1);
15 IkiWiki::loadplugin("filecheck");
25 allowed_attachments => {
27 example => "virusfree() and mimetype(image/*) and maxsize(50kb)",
28 description => "enhanced PageSpec specifying what attachments are allowed",
29 link => "ikiwiki/PageSpec/attachment",
35 example => "clamdscan -",
36 description => "virus checker program (reads STDIN, returns nonzero if virus found)",
42 sub check_canattach ($$;$) {
44 my $dest=shift; # where it's going to be put, under the srcdir
45 my $file=shift; # the path to the attachment currently
47 # Don't allow an attachment to be uploaded with the same name as an
49 if (exists $IkiWiki::pagesources{$dest} &&
50 $IkiWiki::pagesources{$dest} ne $dest) {
51 error(sprintf(gettext("there is already a page named %s"), $dest));
54 # Use a special pagespec to test that the attachment is valid.
56 if (defined $config{allowed_attachments} &&
57 length $config{allowed_attachments}) {
58 $allowed=pagespec_match($dest,
59 $config{allowed_attachments},
61 user => $session->param("name"),
62 ip => $session->remote_addr(),
67 error(gettext("prohibited by allowed_attachments")." ($allowed)");
75 $config{cgi_disable_uploads}=0;
78 sub formbuilder_setup (@) {
80 my $form=$params{form};
83 if (defined $form->field("do") && ($form->field("do") eq "edit" ||
84 $form->field("do") eq "create")) {
85 # Add attachment field, set type to multipart.
86 $form->enctype(&CGI::MULTIPART);
87 $form->field(name => 'attachment', type => 'file');
88 # These buttons are not put in the usual place, so
89 # are not added to the normal formbuilder button list.
90 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
91 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
93 # Add all the javascript used by the attachments interface.
94 require IkiWiki::Plugin::toggle;
95 my $js=IkiWiki::Plugin::toggle::include_javascript($params{page});
96 $js.='<link rel="stylesheet" href="'.urlto("ikiwiki/jquery-ui.css", $params{page}).' id="theme">\n';
97 my @jsfiles=qw{jquery.min jquery-ui.min
98 jquery.tmpl.min jquery.iframe-transport
99 jquery.fileupload jquery.fileupload-ui
101 foreach my $file (@jsfiles) {
102 $js.='<script src="'.urlto("ikiwiki/$file.js", $params{page}).
103 '" type="text/javascript" charset="utf-8"></script>'."\n";
105 $form->tmpl_param("javascript" => $js);
107 # Start with the attachments interface toggled invisible,
108 # but if it was used, keep it open.
109 if ($form->submitted ne "Upload Attachment" &&
110 (! defined $q->param("attachment_select") ||
111 ! length $q->param("attachment_select"))) {
112 $form->tmpl_param("attachments-class" => "toggleable");
115 $form->tmpl_param("attachments-class" => "toggleable-open");
118 # Save attachments in holding area before previewing so
119 # they can be seen in the preview.
120 if ($form->submitted eq "Preview") {
121 attachments_save($form, $params{session});
126 sub formbuilder (@) {
128 my $form=$params{form};
131 return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
133 my $filename=Encode::decode_utf8($q->param('attachment'));
134 if (defined $filename && length $filename) {
135 attachment_store($filename, $form, $q, $params{session});
138 if ($form->submitted eq "Save Page") {
139 attachments_save($form, $params{session});
142 if ($form->submitted eq "Insert Links") {
143 my $page=quotemeta(Encode::decode_utf8($q->param("page")));
145 foreach my $f ($q->param("attachment_select")) {
146 $f=Encode::decode_utf8($f);
148 if (IkiWiki::isinlinableimage($f) &&
149 UNIVERSAL::can("IkiWiki::Plugin::img", "import")) {
150 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
157 $form->field(name => 'editcontent',
158 value => $form->field('editcontent')."\n\n".$add,
159 force => 1) if length $add;
162 # Generate the attachment list only after having added any new
164 $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
167 sub attachment_holding_location {
168 my $page=attachment_location(shift);
170 my $dir=$config{wikistatedir}."/attachments/".
171 IkiWiki::possibly_foolish_untaint(linkpage($page));
176 sub is_held_attachment {
177 my $attachment=shift;
179 my $f=attachment_holding_location($attachment);
188 # Stores the attachment in a holding area, not yet in the wiki proper.
189 sub attachment_store {
195 # This is an (apparently undocumented) way to get the name
196 # of the temp file that CGI writes the upload to.
197 my $tempfile=$q->tmpFileName($filename);
198 if (! defined $tempfile || ! length $tempfile) {
199 # perl 5.8 needs an alternative, awful method
200 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
201 foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
202 $tempfile=$q->tmpFileName(\$key);
203 last if defined $tempfile && length $tempfile;
206 if (! defined $tempfile || ! length $tempfile) {
207 error("CGI::tmpFileName failed to return the uploaded file name");
211 $filename=IkiWiki::basename($filename);
212 $filename=~s/.*\\+(.+)/$1/; # hello, windows
213 $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
215 # Check that the user is allowed to edit the attachment.
217 linkpage(IkiWiki::possibly_foolish_untaint(
218 attachment_location($form->field('page')))).
220 if (IkiWiki::file_pruned($final_filename)) {
221 error(gettext("bad attachment filename"));
223 IkiWiki::check_canedit($final_filename, $q, $session);
224 # And that the attachment itself is acceptable.
225 check_canattach($session, $final_filename, $tempfile);
227 # Move the attachment into holding directory.
228 # Try to use a fast rename; fall back to copying.
229 my $dest=attachment_holding_location($form->field('page'));
230 IkiWiki::prep_writefile($filename, $dest);
231 unlink($dest."/".$filename);
232 if (rename($tempfile, $dest."/".$filename)) {
233 # The temp file has tight permissions; loosen up.
234 chmod(0666 & ~umask, $dest."/".$filename);
237 my $fh=$q->upload('attachment');
238 if (! defined $fh || ! ref $fh) {
239 # needed by old CGI versions
240 $fh=$q->param('attachment');
241 if (! defined $fh || ! ref $fh) {
242 # even that doesn't always work,
243 # fall back to opening the tempfile
245 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
249 require IkiWiki::Render;
250 writefile($filename, $dest, undef, 1, sub {
251 IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
255 # Return JSON response for the jquery file upload widget.
258 print "Content-type: application/json\n\n";
259 my $size=-s $dest."/".$filename;
264 humansize => IkiWiki::Plugin::filecheck::humansize($size),
265 stored_msg => stored_msg(),
272 # Save all stored attachments for a page.
273 sub attachments_save {
277 # Move attachments out of holding directory.
279 my $dir=attachment_holding_location($form->field('page'));
280 foreach my $filename (glob("$dir/*")) {
281 next unless -f $filename;
282 my $dest=$config{srcdir}."/".
283 linkpage(IkiWiki::possibly_foolish_untaint(
284 attachment_location($form->field('page')))).
285 IkiWiki::basename($filename);
287 rename($filename, $dest);
288 push @attachments, $dest;
290 return unless @attachments;
291 require IkiWiki::Render;
292 IkiWiki::prune($dir);
294 # Check the attachments in and trigger a wiki refresh.
296 IkiWiki::rcs_add($_) foreach @attachments;
297 IkiWiki::disable_commit_hook();
298 IkiWiki::rcs_commit_staged(
299 message => gettext("attachment upload"),
302 IkiWiki::enable_commit_hook();
303 IkiWiki::rcs_update();
306 IkiWiki::saveindex();
309 sub attachment_location ($) {
312 # Put the attachment in a subdir of the page it's attached
313 # to, unless that page is an "index" page.
314 $page=~s/(^|\/)index//;
315 $page.="/" if length $page;
320 sub attachment_list ($) {
322 my $loc=attachment_location($page);
331 size => IkiWiki::Plugin::filecheck::humansize($size),
336 # attachments already in the wiki
338 foreach my $f (values %pagesources) {
339 if (! defined pagetype($f) &&
340 $f=~m/^\Q$loc\E[^\/]+$/) {
342 $std->($f, $IkiWiki::pagemtime{$f}, displaytime($IkiWiki::pagemtime{$f}), (stat($f))[7]),
343 link => htmllink($page, $page, $f, noimageinline => 1),
348 # attachments in holding directory
349 my $dir=attachment_holding_location($page);
350 my $heldmsg=gettext("this attachment is not yet saved");
351 foreach my $file (glob("$dir/*")) {
352 next unless -f $file;
353 my $base=IkiWiki::basename($file);
356 $std->($f, (stat($file))[9], stored_msg(), (stat(_))[7]),
361 # Sort newer attachments to the end of the list.
362 return sort { $a->{mtime_raw} <=> $b->{mtime_raw} || $a->{link} cmp $b->{link} }
367 gettext("just uploaded");