]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/attachment.pm
another example error i get
[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 and
120                 # saving.
121                 if ($form->submitted eq "Preview" ||
122                     $form->submitted eq "Save Page") {
123                         attachments_save($form, $params{session});
124                 }
125         }
128 sub formbuilder (@) {
129         my %params=@_;
130         my $form=$params{form};
131         my $q=$params{cgi};
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});
140         }
142         if ($form->submitted eq "Save Page") {
143                 attachments_save($form, $params{session});
144         }
146         if ($form->submitted eq "Insert Links") {
147                 my $page=quotemeta(Encode::decode_utf8(scalar $q->param("page")));
148                 my $add="";
149                 foreach my $f (@{$q->param_fetch("attachment_select")}) {
150                         $f=Encode::decode_utf8($f);
151                         $f=~s/^$page\///;
152                         if (IkiWiki::isinlinableimage($f) &&
153                             IkiWiki::Plugin::img->can("import")) {
154                                 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
155                         }
156                         else {
157                                 $add.="[[$f]]";
158                         }
159                         $add.="\n";
160                 }
161                 my $content = $form->field('editcontent');
162                 $form->field(name => 'editcontent',
163                         value => $content."\n\n".$add,
164                         force => 1) if length $add;
165         }
166         
167         # Generate the attachment list only after having added any new
168         # attachments.
169         $form->tmpl_param("attachment_list" => [attachment_list(scalar $form->field('page'))]);
172 sub attachment_holding_location {
173         my $page=attachment_location(shift);
175         my $dir=$config{wikistatedir}."/attachments/".
176                 IkiWiki::possibly_foolish_untaint(linkpage($page));
177         $dir=~s/\/$//;
178         return $dir;
181 sub is_held_attachment {
182         my $attachment=shift;
184         my $f=attachment_holding_location($attachment);
185         if (-f $f) {
186                 return $f
187         }
188         else {
189                 return undef;
190         }
193 # Stores the attachment in a holding area, not yet in the wiki proper.
194 sub attachment_store {
195         my $filename=shift;
196         my $handle=shift;
197         my $form=shift;
198         my $q=shift;
199         my $session=shift;
201         my $tempfile;
202         if (defined $handle) {
203                 # This is what works in CGI.pm 4.09+: $q->tmpFileName($q->upload('attachment'))
204                 $tempfile=$q->tmpFileName($handle);
205         }
206         if (! defined $tempfile || ! length $tempfile) {
207                 # This is what is *documented* in CGI.pm 4.09: $q->tmpFileName($q->param('attachment'))
208                 $tempfile=$q->tmpFileName($filename);
209         }
210         if (! defined $tempfile || ! length $tempfile) {
211                 # perl 5.8 needs an alternative, awful method
212                 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
213                         foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
214                                 $tempfile=$q->tmpFileName(\$key);
215                                 last if defined $tempfile && length $tempfile;
216                         }
217                 }
218         }
219         if (! defined $tempfile || ! length $tempfile) {
220                 error("CGI::tmpFileName failed to return the uploaded file name");
221         }
223         $filename=IkiWiki::basename($filename);
224         $filename=~s/.*\\+(.+)/$1/; # hello, windows
225         $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
226         my $dest=attachment_holding_location(scalar $form->field('page'));
227         
228         # Check that the user is allowed to edit the attachment.
229         my $final_filename=
230                 linkpage(IkiWiki::possibly_foolish_untaint(
231                         attachment_location(scalar $form->field('page')))).
232                 $filename;
233         eval {
234                 if (IkiWiki::file_pruned($final_filename)) {
235                         error(gettext("bad attachment filename"));
236                 }
237                 IkiWiki::check_canedit($final_filename, $q, $session);
238                 # And that the attachment itself is acceptable.
239                 check_canattach($session, $final_filename, $tempfile);
240         };
241         if ($@) {
242                 # save error in case called functions clobber $@
243                 my $error = $@;
244                 json_response($q, $form, $dest."/".$filename, $error);
245                 error $error;
246         }
248         # Move the attachment into holding directory.
249         # Try to use a fast rename; fall back to copying.
250         IkiWiki::prep_writefile($filename, $dest);
251         unlink($dest."/".$filename);
252         if (rename($tempfile, $dest."/".$filename)) {
253                 # The temp file has tight permissions; loosen up.
254                 chmod(0666 & ~umask, $dest."/".$filename);
255         }
256         else {
257                 my $fh=$q->upload('attachment');
258                 if (! defined $fh || ! ref $fh) {
259                         # needed by old CGI versions
260                         $fh=$q->param('attachment');
261                         if (! defined $fh || ! ref $fh) {
262                                 # even that doesn't always work,
263                                 # fall back to opening the tempfile
264                                 $fh=undef;
265                                 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
266                         }
267                 }
268                 binmode($fh);
269                 require IkiWiki::Render; 
270                 writefile($filename, $dest, undef, 1, sub {
271                         IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
272                 });
273         }
275         json_response($q, $form, $dest."/".$filename, stored_msg());
278 # Save all stored attachments for a page.
279 sub attachments_save {
280         my $form=shift;
281         my $session=shift;
283         # Move attachments out of holding directory.
284         my @attachments;
285         my $dir=attachment_holding_location(scalar $form->field('page'));
286         foreach my $filename (glob("$dir/*")) {
287                 $filename=Encode::decode_utf8($filename);
288                 next unless -f $filename;
289                 my $destdir=linkpage(IkiWiki::possibly_foolish_untaint(
290                         attachment_location(scalar $form->field('page'))));
291                 my $absdestdir=$config{srcdir}."/".$destdir;
292                 my $destfile=IkiWiki::basename($filename);
293                 my $dest=$absdestdir.$destfile;
294                 unlink($dest);
295                 IkiWiki::prep_writefile($destfile, $absdestdir);
296                 rename($filename, $dest);
297                 push @attachments, $destdir.$destfile;
298         }
299         return unless @attachments;
300         require IkiWiki::Render;
301         IkiWiki::prune($dir, $config{wikistatedir}."/attachments");
303         # Check the attachments in and trigger a wiki refresh.
304         if ($config{rcs}) {
305                 IkiWiki::rcs_add($_) foreach @attachments;
306                 IkiWiki::disable_commit_hook();
307                 IkiWiki::rcs_commit_staged(
308                         message => gettext("attachment upload"),
309                         session => $session,
310                 );
311                 IkiWiki::enable_commit_hook();
312                 IkiWiki::rcs_update();
313         }
314         IkiWiki::refresh();
315         IkiWiki::saveindex();
318 sub attachment_location ($) {
319         my $page=shift;
320         
321         # Put the attachment in a subdir of the page it's attached
322         # to, unless that page is the "index" page.
323         return "" if $page eq 'index';
324         $page.="/" if length $page;
325         
326         return $page;
329 sub attachment_list ($) {
330         my $page=shift;
331         my $loc=attachment_location($page);
333         my $std=sub {
334                 my $file=shift;
335                 my $mtime=shift;
336                 my $date=shift;
337                 my $size=shift;
339                 name => $file,
340                 size => IkiWiki::Plugin::filecheck::humansize($size),
341                 mtime => $date,
342                 mtime_raw => $mtime,
343         };
345         # attachments already in the wiki
346         my %attachments;
347         foreach my $f (values %pagesources) {
348                 if (! defined pagetype($f) &&
349                     $f=~m/^\Q$loc\E[^\/]+$/) {
350                         $attachments{$f}={
351                                 $std->($f, $IkiWiki::pagemtime{$f}, displaytime($IkiWiki::pagemtime{$f}), (stat($f))[7]),
352                                 link => htmllink($page, $page, $f, noimageinline => 1),
353                         };
354                 }
355         }
356         
357         # attachments in holding directory
358         my $dir=attachment_holding_location($page);
359         my $heldmsg=gettext("this attachment is not yet saved");
360         foreach my $file (glob("$dir/*")) {
361                 $file=Encode::decode_utf8($file);
362                 next unless -f $file;
363                 my $base=IkiWiki::basename($file);
364                 my $f=$loc.$base;
365                 $attachments{$f}={
366                         $std->($f, (stat($file))[9]*2, stored_msg(), (stat(_))[7]),
367                         link => $base,
368                 }
369         }
371         # Sort newer attachments to the end of the list.
372         return sort { $a->{mtime_raw} <=> $b->{mtime_raw} || $a->{link} cmp $b->{link} }
373                 values %attachments;
376 sub stored_msg {
377         gettext("just uploaded");
380 sub json_response ($$$$) {
381         my $q=shift;
382         my $form=shift;
383         my $filename=shift;
384         my $stored_msg=shift;
386         if (! defined $form->submitted ||
387             $form->submitted ne "Upload Attachment") {
388                 eval q{use JSON};
389                 error $@ if $@;
390                 print "Content-type: text/html\n\n";
391                 my $size=-s $filename;
392                 print to_json([
393                         {
394                                 name => IkiWiki::basename($filename),
395                                 size => $size,
396                                 humansize => IkiWiki::Plugin::filecheck::humansize($size),
397                                 stored_msg => $stored_msg,
398                                 
399                         }
400                 ]);
401                 exit 0;
402         }