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