summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/attachment.pm
blob: 3fe33c858ae849f7314a2e33ab9a40d946f259f6 (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 $page=quotemeta($q->param("page"));
  190. my $add="";
  191. foreach my $f ($q->param("attachment_select")) {
  192. $f=~s/^$page\///;
  193. $add.="[[$f]]\n";
  194. }
  195. $form->field(name => 'editcontent',
  196. value => $form->field('editcontent')."\n\n".$add,
  197. force => 1) if length $add;
  198. }
  199. # Generate the attachment list only after having added any new
  200. # attachments.
  201. $form->tmpl_param("attachment_list" => [attachment_list($form->field('page'))]);
  202. } # }}}
  203. sub attachment_location ($) { #{{{
  204. my $page=shift;
  205. # Put the attachment in a subdir of the page it's attached
  206. # to, unless that page is an "index" page.
  207. $page=~s/(^|\/)index//;
  208. $page.="/" if length $page;
  209. return $page;
  210. } #}}}
  211. sub attachment_list ($) { #{{{
  212. my $page=shift;
  213. my $loc=attachment_location($page);
  214. my @ret;
  215. foreach my $f (values %pagesources) {
  216. if (! defined IkiWiki::pagetype($f) &&
  217. $f=~m/^\Q$loc\E[^\/]+$/ &&
  218. -e "$config{srcdir}/$f") {
  219. push @ret, {
  220. "field-select" => '<input type="checkbox" name="attachment_select" value="'.$f.'" />',
  221. link => htmllink($page, $page, $f, noimageinline => 1),
  222. size => humansize((stat(_))[7]),
  223. mtime => displaytime($IkiWiki::pagemtime{$f}),
  224. mtime_raw => $IkiWiki::pagemtime{$f},
  225. };
  226. }
  227. }
  228. # Sort newer attachments to the top of the list, so a newly-added
  229. # attachment appears just before the form used to add it.
  230. return sort { $b->{mtime_raw} <=> $a->{mtime_raw} || $a->{link} cmp $b->{link} } @ret;
  231. } #}}}
  232. my %units=( #{{{ # size in bytes
  233. B => 1,
  234. byte => 1,
  235. KB => 2 ** 10,
  236. kilobyte => 2 ** 10,
  237. K => 2 ** 10,
  238. KB => 2 ** 10,
  239. kilobyte => 2 ** 10,
  240. M => 2 ** 20,
  241. MB => 2 ** 20,
  242. megabyte => 2 ** 20,
  243. G => 2 ** 30,
  244. GB => 2 ** 30,
  245. gigabyte => 2 ** 30,
  246. T => 2 ** 40,
  247. TB => 2 ** 40,
  248. terabyte => 2 ** 40,
  249. P => 2 ** 50,
  250. PB => 2 ** 50,
  251. petabyte => 2 ** 50,
  252. E => 2 ** 60,
  253. EB => 2 ** 60,
  254. exabyte => 2 ** 60,
  255. Z => 2 ** 70,
  256. ZB => 2 ** 70,
  257. zettabyte => 2 ** 70,
  258. Y => 2 ** 80,
  259. YB => 2 ** 80,
  260. yottabyte => 2 ** 80,
  261. # ikiwiki, if you find you need larger data quantities, either modify
  262. # yourself to add them, or travel back in time to 2008 and kill me.
  263. # -- Joey
  264. ); #}}}
  265. sub parsesize ($) { #{{{
  266. my $size=shift;
  267. no warnings;
  268. my $base=$size+0; # force to number
  269. use warnings;
  270. foreach my $unit (sort keys %units) {
  271. if ($size=~/[0-9\s]\Q$unit\E$/i) {
  272. return $base * $units{$unit};
  273. }
  274. }
  275. return $base;
  276. } #}}}
  277. sub humansize ($) { #{{{
  278. my $size=shift;
  279. foreach my $unit (reverse sort { $units{$a} <=> $units{$b} || $b cmp $a } keys %units) {
  280. if ($size / $units{$unit} > 0.25) {
  281. return (int($size / $units{$unit} * 10)/10).$unit;
  282. }
  283. }
  284. return $size; # near zero, or negative
  285. } #}}}
  286. package IkiWiki::PageSpec;
  287. sub match_maxsize ($$;@) { #{{{
  288. shift;
  289. my $maxsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
  290. if ($@) {
  291. return IkiWiki::FailReason->new("unable to parse maxsize (or number too large)");
  292. }
  293. my %params=@_;
  294. if (! exists $params{file}) {
  295. return IkiWiki::FailReason->new("no file specified");
  296. }
  297. if (-s $params{file} > $maxsize) {
  298. return IkiWiki::FailReason->new("file too large (".(-s $params{file})." > $maxsize)");
  299. }
  300. else {
  301. return IkiWiki::SuccessReason->new("file not too large");
  302. }
  303. } #}}}
  304. sub match_minsize ($$;@) { #{{{
  305. shift;
  306. my $minsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
  307. if ($@) {
  308. return IkiWiki::FailReason->new("unable to parse minsize (or number too large)");
  309. }
  310. my %params=@_;
  311. if (! exists $params{file}) {
  312. return IkiWiki::FailReason->new("no file specified");
  313. }
  314. if (-s $params{file} < $minsize) {
  315. return IkiWiki::FailReason->new("file too small");
  316. }
  317. else {
  318. return IkiWiki::SuccessReason->new("file not too small");
  319. }
  320. } #}}}
  321. sub match_mimetype ($$;@) { #{{{
  322. shift;
  323. my $wanted=shift;
  324. my %params=@_;
  325. if (! exists $params{file}) {
  326. return IkiWiki::FailReason->new("no file specified");
  327. }
  328. # Use ::magic to get the mime type, the idea is to only trust
  329. # data obtained by examining the actual file contents.
  330. eval q{use File::MimeInfo::Magic};
  331. if ($@) {
  332. return IkiWiki::FailReason->new("failed to load File::MimeInfo::Magic ($@); cannot check MIME type");
  333. }
  334. my $mimetype=File::MimeInfo::Magic::magic($params{file});
  335. if (! defined $mimetype) {
  336. $mimetype="unknown";
  337. }
  338. my $regexp=IkiWiki::glob2re($wanted);
  339. if ($mimetype!~/^$regexp$/i) {
  340. return IkiWiki::FailReason->new("file MIME type is $mimetype, not $wanted");
  341. }
  342. else {
  343. return IkiWiki::SuccessReason->new("file MIME type is $mimetype");
  344. }
  345. } #}}}
  346. sub match_virusfree ($$;@) { #{{{
  347. shift;
  348. my $wanted=shift;
  349. my %params=@_;
  350. if (! exists $params{file}) {
  351. return IkiWiki::FailReason->new("no file specified");
  352. }
  353. if (! exists $IkiWiki::config{virus_checker} ||
  354. ! length $IkiWiki::config{virus_checker}) {
  355. return IkiWiki::FailReason->new("no virus_checker configured");
  356. }
  357. # The file needs to be fed into the virus checker on stdin,
  358. # because the file is not world-readable, and if clamdscan is
  359. # used, clamd would fail to read it.
  360. eval q{use IPC::Open2};
  361. error($@) if $@;
  362. open (IN, "<", $params{file}) || return IkiWiki::FailReason->new("failed to read file");
  363. binmode(IN);
  364. my $sigpipe=0;
  365. $SIG{PIPE} = sub { $sigpipe=1 };
  366. my $pid=open2(\*CHECKER_OUT, "<&IN", $IkiWiki::config{virus_checker});
  367. my $reason=<CHECKER_OUT>;
  368. chomp $reason;
  369. 1 while (<CHECKER_OUT>);
  370. close(CHECKER_OUT);
  371. waitpid $pid, 0;
  372. $SIG{PIPE}="DEFAULT";
  373. if ($sigpipe || $?) {
  374. if (! length $reason) {
  375. $reason="virus checker $IkiWiki::config{virus_checker}; failed with no output";
  376. }
  377. return IkiWiki::FailReason->new("file seems to contain a virus ($reason)");
  378. }
  379. else {
  380. return IkiWiki::SuccessReason->new("file seems virusfree ($reason)");
  381. }
  382. } #}}}
  383. sub match_ispage ($$;@) { #{{{
  384. my $filename=shift;
  385. if (defined IkiWiki::pagetype($filename)) {
  386. return IkiWiki::SuccessReason->new("file is a wiki page");
  387. }
  388. else {
  389. return IkiWiki::FailReason->new("file is not a wiki page");
  390. }
  391. } #}}}
  392. sub match_user ($$;@) { #{{{
  393. shift;
  394. my $user=shift;
  395. my %params=@_;
  396. if (! exists $params{user}) {
  397. return IkiWiki::FailReason->new("no user specified");
  398. }
  399. if (defined $params{user} && lc $params{user} eq lc $user) {
  400. return IkiWiki::SuccessReason->new("user is $user");
  401. }
  402. elsif (! defined $params{user}) {
  403. return IkiWiki::FailReason->new("not logged in");
  404. }
  405. else {
  406. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  407. }
  408. } #}}}
  409. sub match_ip ($$;@) { #{{{
  410. shift;
  411. my $ip=shift;
  412. my %params=@_;
  413. if (! exists $params{ip}) {
  414. return IkiWiki::FailReason->new("no IP specified");
  415. }
  416. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  417. return IkiWiki::SuccessReason->new("IP is $ip");
  418. }
  419. else {
  420. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  421. }
  422. } #}}}
  423. 1