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