avoid uninitialised value warnings
[ikiwiki.git] / IkiWiki / Plugin / attachment.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::attachment;
3
4 use warnings;
5 use strict;
6 use IkiWiki 2.00;
7
8 sub import { #{{{
9         hook(type => "checkconfig", id => "attachment", call => \&checkconfig);
10         hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
11         hook(type => "formbuilder", id => "attachment", call => \&formbuilder);
12 } # }}}
13
14 sub checkconfig () { #{{{
15         $config{cgi_disable_uploads}=0;
16 } #}}}
17
18 sub formbuilder_setup (@) { #{{{
19         my %params=@_;
20         my $form=$params{form};
21         my $q=$params{cgi};
22
23         if (defined $form->field("do") && $form->field("do") eq "edit") {
24                 $form->field(name => 'attachment', type => 'file');
25                 # These buttons are not put in the usual place, so
26                 # are not added to the normal formbuilder button list.
27                 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
28                 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
29
30                 # Add the javascript from the toggle plugin;
31                 # the attachments interface uses it to toggle visibility.
32                 require IkiWiki::Plugin::toggle;
33                 $form->tmpl_param("javascript" => $IkiWiki::Plugin::toggle::javascript);
34                 # Start with the attachments interface toggled invisible,
35                 # but if it was used, keep it open.
36                 if ($form->submitted ne "Upload Attachment" &&
37                     ! length $q->param("attachment_select")) {
38                         $form->tmpl_param("attachments-class" => "toggleable");
39                 }
40                 else {
41                         $form->tmpl_param("attachments-class" => "toggleable-open");
42                 }
43         }
44         elsif ($form->title eq "preferences") {
45                 my $session=$params{session};
46                 my $user_name=$session->param("name");
47
48                 $form->field(name => "allowed_attachments", size => 50,
49                         fieldset => "admin",
50                         comment => "(".
51                                 htmllink("", "", 
52                                         "ikiwiki/PageSpec/attachment", 
53                                         noimageinline => 1,
54                                         linktext => "Enhanced PageSpec",
55                                 ).")"
56                 );
57                 if (! IkiWiki::is_admin($user_name)) {
58                         $form->field(name => "allowed_attachments", type => "hidden");
59                 }
60                 if (! $form->submitted) {
61                         $form->field(name => "allowed_attachments", force => 1,
62                                 value => IkiWiki::userinfo_get($user_name, "allowed_attachments"));
63                 }
64                 if ($form->submitted && $form->submitted eq 'Save Preferences') {
65                         if (defined $form->field("allowed_attachments")) {
66                                 IkiWiki::userinfo_set($user_name, "allowed_attachments",
67                                 $form->field("allowed_attachments")) ||
68                                         error("failed to set allowed_attachments");
69                         }
70                 }
71         }
72 } #}}}
73
74 sub formbuilder (@) { #{{{
75         my %params=@_;
76         my $form=$params{form};
77         my $q=$params{cgi};
78
79         return if ! defined $form->field("do") || $form->field("do") ne "edit";
80
81         my $filename=$q->param('attachment');
82         if (defined $filename && length $filename &&
83             ($form->submitted eq "Upload Attachment" || $form->submitted eq "Save Page")) {
84                 my $session=$params{session};
85                 
86                 # This is an (apparently undocumented) way to get the name
87                 # of the temp file that CGI writes the upload to.
88                 my $tempfile=$q->tmpFileName($filename);
89                 
90                 $filename=IkiWiki::titlepage(
91                         IkiWiki::possibly_foolish_untaint(
92                                 attachment_location($form->field('page')).
93                                 IkiWiki::basename($filename)));
94                 if (IkiWiki::file_pruned($filename, $config{srcdir})) {
95                         error(gettext("bad attachment filename"));
96                 }
97                 
98                 # Check that the user is allowed to edit a page with the
99                 # name of the attachment.
100                 IkiWiki::check_canedit($filename, $q, $session, 1);
101                 
102                 # Use a special pagespec to test that the attachment is valid.
103                 my $allowed=1;
104                 foreach my $admin (@{$config{adminuser}}) {
105                         my $allowed_attachments=IkiWiki::userinfo_get($admin, "allowed_attachments");
106                         if (defined $allowed_attachments &&
107                             length $allowed_attachments) {
108                                 $allowed=pagespec_match($filename,
109                                         $allowed_attachments,
110                                         file => $tempfile,
111                                         user => $session->param("name"),
112                                         ip => $ENV{REMOTE_ADDR},
113                                 );
114                                 last if $allowed;
115                         }
116                 }
117                 if (! $allowed) {
118                         error(gettext("attachment rejected")." ($allowed)");
119                 }
120
121                 # Needed for fast_file_copy and for rendering below.
122                 require IkiWiki::Render;
123
124                 # Move the attachment into place.
125                 # Try to use a fast rename; fall back to copying.
126                 IkiWiki::prep_writefile($filename, $config{srcdir});
127                 unlink($config{srcdir}."/".$filename);
128                 if (rename($tempfile, $config{srcdir}."/".$filename)) {
129                         # The temp file has tight permissions; loosen up.
130                         chmod(0666 & ~umask, $config{srcdir}."/".$filename);
131                 }
132                 else {
133                         my $fh=$q->upload('attachment');
134                         if (! defined $fh || ! ref $fh) {
135                                 error("failed to get filehandle");
136                         }
137                         binmode($fh);
138                         writefile($filename, $config{srcdir}, undef, 1, sub {
139                                 IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
140                         });
141                 }
142
143                 # Check the attachment in and trigger a wiki refresh.
144                 if ($config{rcs}) {
145                         IkiWiki::rcs_add($filename);
146                         IkiWiki::disable_commit_hook();
147                         IkiWiki::rcs_commit($filename, gettext("attachment upload"),
148                                 IkiWiki::rcs_prepedit($filename),
149                                 $session->param("name"), $ENV{REMOTE_ADDR});
150                         IkiWiki::enable_commit_hook();
151                         IkiWiki::rcs_update();
152                 }
153                 IkiWiki::refresh();
154                 IkiWiki::saveindex();
155         }
156         elsif ($form->submitted eq "Insert Links") {
157                 my $add="";
158                 foreach my $f ($q->param("attachment_select")) {
159                         $add.="[[$f]]\n";
160                 }
161                 $form->field(name => 'editcontent',
162                         value => $form->field('editcontent')."\n\n".$add,
163                         force => 1) if length $add;
164         }
165         
166         # Generate the attachment list only after having added any new
167         # attachments.
168         $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
169 } # }}}
170
171 sub attachment_location ($) {
172         my $page=shift;
173         
174         # Put the attachment in a subdir of the page it's attached
175         # to, unless that page is an "index" page.
176         $page=~s/(^|\/)index//;
177         $page.="/" if length $page;
178         
179         return $page;
180 }
181
182 sub attachment_list ($) {
183         my $page=shift;
184         my $loc=attachment_location($page);
185
186         my @ret;
187         foreach my $f (values %pagesources) {
188                 if (! defined IkiWiki::pagetype($f) &&
189                     $f=~m/^\Q$loc\E[^\/]+$/ &&
190                     -e "$config{srcdir}/$f") {
191                         push @ret, {
192                                 "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
193                                 link => htmllink($page, $page, $f, noimageinline => 1),
194                                 size => humansize((stat(_))[7]),
195                                 mtime => displaytime($IkiWiki::pagemtime{$f}),
196                                 mtime_raw => $IkiWiki::pagemtime{$f},
197                         };
198                 }
199         }
200
201         # Sort newer attachments to the top of the list, so a newly-added
202         # attachment appears just before the form used to add it.
203         return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} } @ret;
204 }
205
206 my %units=(             # size in bytes
207         B               => 1,
208         byte            => 1,
209         KB              => 2 ** 10,
210         kilobyte        => 2 ** 10,
211         K               => 2 ** 10,
212         KB              => 2 ** 10,
213         kilobyte        => 2 ** 10,
214         M               => 2 ** 20,
215         MB              => 2 ** 20,
216         megabyte        => 2 ** 20,
217         G               => 2 ** 30,
218         GB              => 2 ** 30,
219         gigabyte        => 2 ** 30,
220         T               => 2 ** 40,
221         TB              => 2 ** 40,
222         terabyte        => 2 ** 40,
223         P               => 2 ** 50,
224         PB              => 2 ** 50,
225         petabyte        => 2 ** 50,
226         E               => 2 ** 60,
227         EB              => 2 ** 60,
228         exabyte         => 2 ** 60,
229         Z               => 2 ** 70,
230         ZB              => 2 ** 70,
231         zettabyte       => 2 ** 70,
232         Y               => 2 ** 80,
233         YB              => 2 ** 80,
234         yottabyte       => 2 ** 80,
235         # ikiwiki, if you find you need larger data quantities, either modify
236         # yourself to add them, or travel back in time to 2008 and kill me.
237         #   -- Joey
238 );
239
240 sub parsesize ($) { #{{{
241         my $size=shift;
242
243         no warnings;
244         my $base=$size+0; # force to number
245         use warnings;
246         foreach my $unit (sort keys %units) {
247                 if ($size=~/[0-9\s]\Q$unit\E$/i) {
248                         return $base * $units{$unit};
249                 }
250         }
251         return $base;
252 } #}}}
253
254 sub humansize ($) { #{{{
255         my $size=shift;
256
257         foreach my $unit (reverse sort { $units{$a} <=> $units{$b} || $b cmp $a } keys %units) {
258                 if ($size / $units{$unit} > 0.25) {
259                         return (int($size / $units{$unit} * 10)/10).$unit;
260                 }
261         }
262         return $size; # near zero, or negative
263 } #}}}
264
265 package IkiWiki::PageSpec;
266
267 sub match_maxsize ($$;@) { #{{{
268         shift;
269         my $maxsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
270         if ($@) {
271                 return IkiWiki::FailReason->new("unable to parse maxsize (or number too large)");
272         }
273
274         my %params=@_;
275         if (! exists $params{file}) {
276                 return IkiWiki::FailReason->new("no file specified");
277         }
278
279         if (-s $params{file} > $maxsize) {
280                 return IkiWiki::FailReason->new("file too large (".(-s $params{file})." >  $maxsize)");
281         }
282         else {
283                 return IkiWiki::SuccessReason->new("file not too large");
284         }
285 } #}}}
286
287 sub match_minsize ($$;@) { #{{{
288         shift;
289         my $minsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
290         if ($@) {
291                 return IkiWiki::FailReason->new("unable to parse minsize (or number too large)");
292         }
293
294         my %params=@_;
295         if (! exists $params{file}) {
296                 return IkiWiki::FailReason->new("no file specified");
297         }
298
299         if (-s $params{file} < $minsize) {
300                 return IkiWiki::FailReason->new("file too small");
301         }
302         else {
303                 return IkiWiki::SuccessReason->new("file not too small");
304         }
305 } #}}}
306
307 sub match_mimetype ($$;@) { #{{{
308         shift;
309         my $wanted=shift;
310
311         my %params=@_;
312         if (! exists $params{file}) {
313                 return IkiWiki::FailReason->new("no file specified");
314         }
315
316         # Use ::magic to get the mime type, the idea is to only trust
317         # data obtained by examining the actual file contents.
318         eval q{use File::MimeInfo::Magic};
319         if ($@) {
320                 return IkiWiki::FailReason->new("failed to load File::MimeInfo::Magic ($@); cannot check MIME type");
321         }
322         my $mimetype=File::MimeInfo::Magic::magic($params{file});
323         if (! defined $mimetype) {
324                 $mimetype="unknown";
325         }
326
327         my $regexp=IkiWiki::glob2re($wanted);
328         if ($mimetype!~/^$regexp$/i) {
329                 return IkiWiki::FailReason->new("file MIME type is $mimetype, not $wanted");
330         }
331         else {
332                 return IkiWiki::SuccessReason->new("file MIME type is $mimetype");
333         }
334 } #}}}
335
336 sub match_ispage ($$;@) { #{{{
337         my $filename=shift;
338
339         if (defined IkiWiki::pagetype($filename)) {
340                 return IkiWiki::SuccessReason->new("file is a wiki page");
341         }
342         else {
343                 return IkiWiki::FailReason->new("file is not a wiki page");
344         }
345 } #}}}
346
347 sub match_user ($$;@) { #{{{
348         shift;
349         my $user=shift;
350         my %params=@_;
351         
352         if (! exists $params{user}) {
353                 return IkiWiki::FailReason->new("no user specified");
354         }
355
356         if (defined $params{user} && lc $params{user} eq lc $user) {
357                 return IkiWiki::SuccessReason->new("user is $user");
358         }
359         else {
360                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
361         }
362 } #}}}
363
364 sub match_ip ($$;@) { #{{{
365         shift;
366         my $ip=shift;
367         my %params=@_;
368         
369         if (! exists $params{ip}) {
370                 return IkiWiki::FailReason->new("no IP specified");
371         }
372
373         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
374                 return IkiWiki::SuccessReason->new("IP is $ip");
375         }
376         else {
377                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
378         }
379 } #}}}
380
381 1