]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/attachment.pm
improve detection of ajax request
[git.ikiwiki.info.git] / IkiWiki / Plugin / attachment.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::attachment;
4 use warnings;
5 use strict;
6 use IkiWiki 3.00;
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 }
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 }
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
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         }
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         }
67         if (! $allowed) {
68                 error(gettext("prohibited by allowed_attachments")." ($allowed)");
69         }
70         else {
71                 return 1;
72         }
73 }
75 sub checkconfig () {
76         $config{cgi_disable_uploads}=0;
77 }
79 sub formbuilder_setup (@) {
80         my %params=@_;
81         my $form=$params{form};
82         my $q=$params{cgi};
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
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);
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 so
120                 # they can be seen in the preview.
121                 if ($form->submitted eq "Preview") {
122                         attachments_save($form, $params{session});
123                 }
124         }
127 sub formbuilder (@) {
128         my %params=@_;
129         my $form=$params{form};
130         my $q=$params{cgi};
132         return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
134         my $filename=Encode::decode_utf8($q->param('attachment'));
135         if (defined $filename && length $filename) {
136                 attachment_store($filename, $form, $q, $params{session});
137         }
139         if ($form->submitted eq "Save Page") {
140                 attachments_save($form, $params{session});
141         }
143         if ($form->submitted eq "Insert Links") {
144                 my $page=quotemeta(Encode::decode_utf8($q->param("page")));
145                 my $add="";
146                 foreach my $f ($q->param("attachment_select")) {
147                         $f=Encode::decode_utf8($f);
148                         $f=~s/^$page\///;
149                         if (IkiWiki::isinlinableimage($f) &&
150                             UNIVERSAL::can("IkiWiki::Plugin::img", "import")) {
151                                 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
152                         }
153                         else {
154                                 $add.="[[$f]]";
155                         }
156                         $add.="\n";
157                 }
158                 $form->field(name => 'editcontent',
159                         value => $form->field('editcontent')."\n\n".$add,
160                         force => 1) if length $add;
161         }
162         
163         # Generate the attachment list only after having added any new
164         # attachments.
165         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
168 sub attachment_holding_location {
169         my $page=attachment_location(shift);
171         my $dir=$config{wikistatedir}."/attachments/".
172                 IkiWiki::possibly_foolish_untaint(linkpage($page));
173         $dir=~s/\/$//;
174         return $dir;
177 sub is_held_attachment {
178         my $attachment=shift;
180         my $f=attachment_holding_location($attachment);
181         if (-f $f) {
182                 return $f
183         }
184         else {
185                 return undef;
186         }
189 # Stores the attachment in a holding area, not yet in the wiki proper.
190 sub attachment_store {
191         my $filename=shift;
192         my $form=shift;
193         my $q=shift;
194         my $session=shift;
195         
196         # This is an (apparently undocumented) way to get the name
197         # of the temp file that CGI writes the upload to.
198         my $tempfile=$q->tmpFileName($filename);
199         if (! defined $tempfile || ! length $tempfile) {
200                 # perl 5.8 needs an alternative, awful method
201                 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
202                         foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
203                                 $tempfile=$q->tmpFileName(\$key);
204                                 last if defined $tempfile && length $tempfile;
205                         }
206                 }
207                 if (! defined $tempfile || ! length $tempfile) {
208                         error("CGI::tmpFileName failed to return the uploaded file name");
209                 }
210         }
212         $filename=IkiWiki::basename($filename);
213         $filename=~s/.*\\+(.+)/$1/; # hello, windows
214         $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
215         my $dest=attachment_holding_location($form->field('page'));
216         
217         # Check that the user is allowed to edit the attachment.
218         my $final_filename=
219                 linkpage(IkiWiki::possibly_foolish_untaint(
220                         attachment_location($form->field('page')))).
221                 $filename;
222         eval {
223                 if (IkiWiki::file_pruned($final_filename)) {
224                         error(gettext("bad attachment filename"));
225                 }
226                 IkiWiki::check_canedit($final_filename, $q, $session);
227                 # And that the attachment itself is acceptable.
228                 check_canattach($session, $final_filename, $tempfile);
229         };
230         if ($@) {
231                 json_response($q, $form, $dest."/".$filename, $@);
232                 error $@;
233         }
235         # Move the attachment into holding directory.
236         # Try to use a fast rename; fall back to copying.
237         IkiWiki::prep_writefile($filename, $dest);
238         unlink($dest."/".$filename);
239         if (rename($tempfile, $dest."/".$filename)) {
240                 # The temp file has tight permissions; loosen up.
241                 chmod(0666 & ~umask, $dest."/".$filename);
242         }
243         else {
244                 my $fh=$q->upload('attachment');
245                 if (! defined $fh || ! ref $fh) {
246                         # needed by old CGI versions
247                         $fh=$q->param('attachment');
248                         if (! defined $fh || ! ref $fh) {
249                                 # even that doesn't always work,
250                                 # fall back to opening the tempfile
251                                 $fh=undef;
252                                 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
253                         }
254                 }
255                 binmode($fh);
256                 require IkiWiki::Render; 
257                 writefile($filename, $dest, undef, 1, sub {
258                         IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
259                 });
260         }
262         json_response($q, $form, $dest."/".$filename, stored_msg());
265 # Save all stored attachments for a page.
266 sub attachments_save {
267         my $form=shift;
268         my $session=shift;
270         # Move attachments out of holding directory.
271         my @attachments;
272         my $dir=attachment_holding_location($form->field('page'));
273         foreach my $filename (glob("$dir/*")) {
274                 next unless -f $filename;
275                 my $dest=$config{srcdir}."/".
276                         linkpage(IkiWiki::possibly_foolish_untaint(
277                                 attachment_location($form->field('page')))).
278                         IkiWiki::basename($filename);
279                 unlink($dest);
280                 rename($filename, $dest);
281                 push @attachments, $dest;
282         }
283         return unless @attachments;
284         require IkiWiki::Render;
285         IkiWiki::prune($dir);
287         # Check the attachments in and trigger a wiki refresh.
288         if ($config{rcs}) {
289                 IkiWiki::rcs_add($_) foreach @attachments;
290                 IkiWiki::disable_commit_hook();
291                 IkiWiki::rcs_commit_staged(
292                         message => gettext("attachment upload"),
293                         session => $session,
294                 );
295                 IkiWiki::enable_commit_hook();
296                 IkiWiki::rcs_update();
297         }
298         IkiWiki::refresh();
299         IkiWiki::saveindex();
302 sub attachment_location ($) {
303         my $page=shift;
304         
305         # Put the attachment in a subdir of the page it's attached
306         # to, unless that page is an "index" page.
307         $page=~s/(^|\/)index//;
308         $page.="/" if length $page;
309         
310         return $page;
313 sub attachment_list ($) {
314         my $page=shift;
315         my $loc=attachment_location($page);
317         my $std=sub {
318                 my $file=shift;
319                 my $mtime=shift;
320                 my $date=shift;
321                 my $size=shift;
323                 name => $file,
324                 size => IkiWiki::Plugin::filecheck::humansize($size),
325                 mtime => $date,
326                 mtime_raw => $mtime,
327         };
329         # attachments already in the wiki
330         my %attachments;
331         foreach my $f (values %pagesources) {
332                 if (! defined pagetype($f) &&
333                     $f=~m/^\Q$loc\E[^\/]+$/) {
334                         $attachments{$f}={
335                                 $std->($f, $IkiWiki::pagemtime{$f}, displaytime($IkiWiki::pagemtime{$f}), (stat($f))[7]),
336                                 link => htmllink($page, $page, $f, noimageinline => 1),
337                         };
338                 }
339         }
340         
341         # attachments in holding directory
342         my $dir=attachment_holding_location($page);
343         my $heldmsg=gettext("this attachment is not yet saved");
344         foreach my $file (glob("$dir/*")) {
345                 next unless -f $file;
346                 my $base=IkiWiki::basename($file);
347                 my $f=$loc.$base;
348                 $attachments{$f}={
349                         $std->($f, (stat($file))[9]*2, stored_msg(), (stat(_))[7]),
350                         link => $base,
351                 }
352         }
354         # Sort newer attachments to the end of the list.
355         return sort { $a->{mtime_raw} <=> $b->{mtime_raw} || $a->{link} cmp $b->{link} }
356                 values %attachments;
359 sub stored_msg {
360         gettext("just uploaded");
363 sub json_response ($$$$) {
364         my $q=shift;
365         my $form=shift;
366         my $filename=shift;
367         my $stored_msg=shift;
369         if (! defined $form->submitted ||
370             $form->submitted ne "Upload Attachment") {
371                 eval q{use JSON};
372                 error $@ if $@;
373                 print "Content-type: text/html\n\n";
374                 my $size=-s $filename;
375                 print to_json([
376                         {
377                                 name => IkiWiki::basename($filename),
378                                 size => $size,
379                                 humansize => IkiWiki::Plugin::filecheck::humansize($size),
380                                 stored_msg => $stored_msg,
381                                 
382                         }
383                 ]);
384                 exit 0;
385         }