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