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