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