2 package IkiWiki::Plugin::attachment;
8 $CGI::DISABLE_UPLOADS=0;
10 # TODO move to admin prefs
11 $config{valid_attachments}="(*.mp3 and maxsize(15mb)) or (* and maxsize(50kb))";
14 hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
15 hook(type => "formbuilder", id => "attachment", call => \&formbuilder);
18 sub formbuilder_setup { #{{{
20 my $form=$params{form};
22 return if $form->field("do") ne "edit";
24 $form->field(name => 'attachment', type => 'file');
27 sub formbuilder (@) { #{{{
29 my $form=$params{form};
31 return if $form->field("do") ne "edit";
33 if ($form->submitted eq "Upload") {
35 my $filename=IkiWiki::basename($q->param('attachment'));
36 if (! defined $filename || ! length $filename) {
37 # no file, so do nothing
41 # This is an (apparently undocumented) way to get the name
42 # of the temp file that CGI writes the upload to.
43 my $tempfile=$q->tmpFileName($filename);
45 # To untaint the filename, escape any hazardous characters,
46 # and make sure it isn't pruned.
47 $filename=IkiWiki::possibly_foolish_untaint(IkiWiki::titlepage($filename));
48 if (IkiWiki::file_pruned($filename, $config{srcdir})) {
49 error(gettext("bad attachment filename"));
52 # Use a pagespec to test that the attachment is valid.
53 if (exists $config{valid_attachments} &&
54 length $config{valid_attachments}) {
55 my $result=pagespec_match($filename, $config{valid_attachments},
56 tempfile => $tempfile);
58 error(gettext("attachment rejected")." ($result)");
62 my $fh=$q->upload('attachment');
63 if (! defined $fh || ! ref $fh) {
64 error("failed to get filehandle");
73 package IkiWiki::PageSpec;
78 my $base=$size+0; # force to number
84 elsif ($size=~/mb?$/i) {
87 elsif ($size=~/gb?$/i) {
90 elsif ($size=~/tb?$/i) {
93 return $base * $multiple;
96 sub match_maxsize ($$;@) { #{{{
98 my $maxsize=eval{parsesize(shift)};
100 return IkiWiki::FailReason->new("unable to parse maxsize (or number too large)");
104 if (! exists $params{tempfile}) {
105 return IkiWiki::FailReason->new("no tempfile specified");
108 if (-s $params{tempfile} > $maxsize) {
109 return IkiWiki::FailReason->new("attachment too large");
112 return IkiWiki::SuccessReason->new("attachment size ok");
116 sub match_minsize ($$;@) { #{{{
118 my $minsize=eval{parsesize(shift)};
120 return IkiWiki::FailReason->new("unable to parse minsize (or number too large)");
124 if (! exists $params{tempfile}) {
125 return IkiWiki::FailReason->new("no tempfile specified");
128 if (-s $params{tempfile} < $minsize) {
129 return IkiWiki::FailReason->new("attachment too small");
132 return IkiWiki::SuccessReason->new("attachment size ok");