<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl
package IkiWiki::Plugin::attachment;

use warnings;
use strict;
use IkiWiki 3.00;

sub import {
	add_underlay("javascript");
	hook(type =&gt; "getsetup", id =&gt; "attachment", call =&gt; \&amp;getsetup);
	hook(type =&gt; "checkconfig", id =&gt; "attachment", call =&gt; \&amp;checkconfig);
	hook(type =&gt; "formbuilder_setup", id =&gt; "attachment", call =&gt; \&amp;formbuilder_setup);
	hook(type =&gt; "formbuilder", id =&gt; "attachment", call =&gt; \&amp;formbuilder);
	IkiWiki::loadplugin("filecheck");
}

sub getsetup () {
	return
		plugin =&gt; {
			safe =&gt; 1,
			rebuild =&gt; 0,
			section =&gt; "web",
		},
		allowed_attachments =&gt; {
			type =&gt; "pagespec",
			example =&gt; "virusfree() and mimetype(image/*) and maxsize(50kb)",
			description =&gt; "enhanced PageSpec specifying what attachments are allowed",
			link =&gt; "ikiwiki/PageSpec/attachment",
			safe =&gt; 1,
			rebuild =&gt; 0,
		},
		virus_checker =&gt; {
			type =&gt; "string",
			example =&gt; "clamdscan -",
			description =&gt; "virus checker program (reads STDIN, returns nonzero if virus found)",
			safe =&gt; 0, # executed
			rebuild =&gt; 0,
		},
}

sub check_canattach ($$;$) {
	my $session=shift;
	my $dest=shift; # where it's going to be put, under the srcdir
	my $file=shift; # the path to the attachment currently

	# Don't allow an attachment to be uploaded with the same name as an
	# existing page.
	if (exists $IkiWiki::pagesources{$dest} &amp;&amp;
	    $IkiWiki::pagesources{$dest} ne $dest) {
		error(sprintf(gettext("there is already a page named %s"), $dest));
	}

	# Use a special pagespec to test that the attachment is valid.
	my $allowed=1;
	if (defined $config{allowed_attachments} &amp;&amp;
	    length $config{allowed_attachments}) {
		$allowed=pagespec_match($dest,
			$config{allowed_attachments},
			file =&gt; $file,
			user =&gt; $session-&gt;param("name"),
			ip =&gt; $ENV{REMOTE_ADDR},
		);
	}

	if (! $allowed) {
		error(gettext("prohibited by allowed_attachments")." ($allowed)");
	}
	else {
		return 1;
	}
}

sub checkconfig () {
	$config{cgi_disable_uploads}=0;
}

sub formbuilder_setup (@) {
	my %params=@_;
	my $form=$params{form};
	my $q=$params{cgi};

	if (defined $form-&gt;field("do") &amp;&amp; ($form-&gt;field("do") eq "edit" ||
	    $form-&gt;field("do") eq "create")) {
		# Add attachment field, set type to multipart.
		$form-&gt;enctype(&amp;CGI::MULTIPART);
		$form-&gt;field(name =&gt; 'attachment', type =&gt; 'file');
		# These buttons are not put in the usual place, so
		# are not added to the normal formbuilder button list.
		$form-&gt;tmpl_param("field-upload" =&gt; '&lt;input name="_submit" type="submit" value="Upload Attachment" /&gt;');
		$form-&gt;tmpl_param("field-link" =&gt; '&lt;input name="_submit" type="submit" value="Insert Links" /&gt;');

		# Add the toggle javascript; the attachments interface uses
		# it to toggle visibility.
		require IkiWiki::Plugin::toggle;
		$form-&gt;tmpl_param("javascript" =&gt; IkiWiki::Plugin::toggle::include_javascript($params{page}, 1));
		# Start with the attachments interface toggled invisible,
		# but if it was used, keep it open.
		if ($form-&gt;submitted ne "Upload Attachment" &amp;&amp;
		    (! defined $q-&gt;param("attachment_select") ||
		    ! length $q-&gt;param("attachment_select"))) {
			$form-&gt;tmpl_param("attachments-class" =&gt; "toggleable");
		}
		else {
			$form-&gt;tmpl_param("attachments-class" =&gt; "toggleable-open");
		}
	}
}

sub formbuilder (@) {
	my %params=@_;
	my $form=$params{form};
	my $q=$params{cgi};

	return if ! defined $form-&gt;field("do") || ($form-&gt;field("do") ne "edit" &amp;&amp; $form-&gt;field("do") ne "create") ;

	my $filename=Encode::decode_utf8($q-&gt;param('attachment'));
	if (defined $filename &amp;&amp; length $filename &amp;&amp;
            ($form-&gt;submitted eq "Upload Attachment" || $form-&gt;submitted eq "Save Page")) {
		my $session=$params{session};
		
		# This is an (apparently undocumented) way to get the name
		# of the temp file that CGI writes the upload to.
		my $tempfile=$q-&gt;tmpFileName($filename);
		if (! defined $tempfile || ! length $tempfile) {
			# perl 5.8 needs an alternative, awful method
			if ($q =~ /HASH/ &amp;&amp; exists $q-&gt;{'.tmpfiles'}) {
				foreach my $key (keys(%{$q-&gt;{'.tmpfiles'}})) {
					$tempfile=$q-&gt;tmpFileName(\$key);
					last if defined $tempfile &amp;&amp; length $tempfile;
				}
			}
			if (! defined $tempfile || ! length $tempfile) {
				error("CGI::tmpFileName failed to return the uploaded file name");
			}
		}

		$filename=linkpage(IkiWiki::possibly_foolish_untaint(
				attachment_location($form-&gt;field('page')).
				IkiWiki::basename($filename)));
		if (IkiWiki::file_pruned($filename, $config{srcdir})) {
			error(gettext("bad attachment filename"));
		}
		
		# Check that the user is allowed to edit a page with the
		# name of the attachment.
		IkiWiki::check_canedit($filename, $q, $session, 1);
		# And that the attachment itself is acceptable.
		check_canattach($session, $filename, $tempfile);

		# Needed for fast_file_copy and for rendering below.
		require IkiWiki::Render;

		# Move the attachment into place.
		# Try to use a fast rename; fall back to copying.
		IkiWiki::prep_writefile($filename, $config{srcdir});
		unlink($config{srcdir}."/".$filename);
		if (rename($tempfile, $config{srcdir}."/".$filename)) {
			# The temp file has tight permissions; loosen up.
			chmod(0666 &amp; ~umask, $config{srcdir}."/".$filename);
		}
		else {
			my $fh=$q-&gt;upload('attachment');
			if (! defined $fh || ! ref $fh) {
				# needed by old CGI versions
				$fh=$q-&gt;param('attachment');
				if (! defined $fh || ! ref $fh) {
					# even that doesn't always work,
					# fall back to opening the tempfile
					$fh=undef;
					open($fh, "&lt;", $tempfile) || error("failed to open \"$tempfile\": $!");
				}
			}
			binmode($fh);
			writefile($filename, $config{srcdir}, undef, 1, sub {
				IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
			});
		}

		# Check the attachment in and trigger a wiki refresh.
		if ($config{rcs}) {
			IkiWiki::rcs_add($filename);
			IkiWiki::disable_commit_hook();
			IkiWiki::rcs_commit($filename, gettext("attachment upload"),
				IkiWiki::rcs_prepedit($filename),
				$session-&gt;param("name"), $ENV{REMOTE_ADDR});
			IkiWiki::enable_commit_hook();
			IkiWiki::rcs_update();
		}
		IkiWiki::refresh();
		IkiWiki::saveindex();
	}
	elsif ($form-&gt;submitted eq "Insert Links") {
		my $page=quotemeta(Encode::decode_utf8($q-&gt;param("page")));
		my $add="";
		foreach my $f ($q-&gt;param("attachment_select")) {
			$f=Encode::decode_utf8($f);
			$f=~s/^$page\///;
			$add.="[[$f]]\n";
		}
		$form-&gt;field(name =&gt; 'editcontent',
			value =&gt; $form-&gt;field('editcontent')."\n\n".$add,
			force =&gt; 1) if length $add;
	}
	
	# Generate the attachment list only after having added any new
	# attachments.
	$form-&gt;tmpl_param("attachment_list" =&gt; [attachment_list($form-&gt;field('page'))]);
}

sub attachment_location ($) {
	my $page=shift;
	
	# Put the attachment in a subdir of the page it's attached
	# to, unless that page is an "index" page.
	$page=~s/(^|\/)index//;
	$page.="/" if length $page;
	
	return $page;
}

sub attachment_list ($) {
	my $page=shift;
	my $loc=attachment_location($page);

	my @ret;
	foreach my $f (values %pagesources) {
		if (! defined pagetype($f) &amp;&amp;
		    $f=~m/^\Q$loc\E[^\/]+$/ &amp;&amp;
		    -e "$config{srcdir}/$f") {
			push @ret, {
				"field-select" =&gt; '&lt;input type="checkbox" name="attachment_select" value="'.$f.'" /&gt;',
				link =&gt; htmllink($page, $page, $f, noimageinline =&gt; 1),
				size =&gt; IkiWiki::Plugin::filecheck::humansize((stat(_))[7]),
				mtime =&gt; displaytime($IkiWiki::pagemtime{$f}),
				mtime_raw =&gt; $IkiWiki::pagemtime{$f},
			};
		}
	}

	# Sort newer attachments to the top of the list, so a newly-added
	# attachment appears just before the form used to add it.
	return sort { $b-&gt;{mtime_raw} &lt;=&gt; $a-&gt;{mtime_raw} || $a-&gt;{link} cmp $b-&gt;{link} } @ret;
}

1
</pre></body></html>