<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 2.00;

sub import { #{{{
	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);
} # }}}

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 $pagesources{$dest} &amp;&amp; $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;
	foreach my $admin (@{$config{adminuser}}) {
		my $allowed_attachments=IkiWiki::userinfo_get($admin, "allowed_attachments");
		if (defined $allowed_attachments &amp;&amp;
		    length $allowed_attachments) {
			$allowed=pagespec_match($dest,
				$allowed_attachments,
				file =&gt; $file,
				user =&gt; $session-&gt;param("name"),
				ip =&gt; $ENV{REMOTE_ADDR},
			);
			last if $allowed;
		}
	}
	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") {
		# 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 javascript from the toggle plugin;
		# the attachments interface uses it to toggle visibility.
		require IkiWiki::Plugin::toggle;
		$form-&gt;tmpl_param("javascript" =&gt; $IkiWiki::Plugin::toggle::javascript);
		# 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");
		}
	}
	elsif ($form-&gt;title eq "preferences") {
		my $session=$params{session};
		my $user_name=$session-&gt;param("name");

		$form-&gt;field(name =&gt; "allowed_attachments", size =&gt; 50,
			fieldset =&gt; "admin",
			comment =&gt; "(".
				htmllink("", "", 
					"ikiwiki/PageSpec/attachment", 
					noimageinline =&gt; 1,
					linktext =&gt; "Enhanced PageSpec",
				).")"
		);
		if (! IkiWiki::is_admin($user_name)) {
			$form-&gt;field(name =&gt; "allowed_attachments", type =&gt; "hidden");
		}
                if (! $form-&gt;submitted) {
			$form-&gt;field(name =&gt; "allowed_attachments", force =&gt; 1,
				value =&gt; IkiWiki::userinfo_get($user_name, "allowed_attachments"));
                }
		if ($form-&gt;submitted &amp;&amp; $form-&gt;submitted eq 'Save Preferences') {
			if (defined $form-&gt;field("allowed_attachments")) {
				IkiWiki::userinfo_set($user_name, "allowed_attachments",
				$form-&gt;field("allowed_attachments")) ||
					error("failed to set allowed_attachments");
			}
		}
	}
} #}}}

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";

	my $filename=$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=IkiWiki::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($q-&gt;param("page"));
		my $add="";
		foreach my $f ($q-&gt;param("attachment_select")) {
			$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 IkiWiki::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; 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;
} #}}}

my %units=( #{{{	# size in bytes
	B		=&gt; 1,
	byte		=&gt; 1,
	KB		=&gt; 2 ** 10,
	kilobyte 	=&gt; 2 ** 10,
	K		=&gt; 2 ** 10,
	KB		=&gt; 2 ** 10,
	kilobyte 	=&gt; 2 ** 10,
	M		=&gt; 2 ** 20,
	MB		=&gt; 2 ** 20,
	megabyte	=&gt; 2 ** 20,
	G		=&gt; 2 ** 30,
	GB		=&gt; 2 ** 30,
	gigabyte	=&gt; 2 ** 30,
	T		=&gt; 2 ** 40,
	TB		=&gt; 2 ** 40,
	terabyte	=&gt; 2 ** 40,
	P		=&gt; 2 ** 50,
	PB		=&gt; 2 ** 50,
	petabyte	=&gt; 2 ** 50,
	E		=&gt; 2 ** 60,
	EB		=&gt; 2 ** 60,
	exabyte		=&gt; 2 ** 60,
	Z		=&gt; 2 ** 70,
	ZB		=&gt; 2 ** 70,
	zettabyte	=&gt; 2 ** 70,
	Y		=&gt; 2 ** 80,
	YB		=&gt; 2 ** 80,
	yottabyte	=&gt; 2 ** 80,
	# ikiwiki, if you find you need larger data quantities, either modify
	# yourself to add them, or travel back in time to 2008 and kill me.
	#   -- Joey
); #}}}

sub parsesize ($) { #{{{
	my $size=shift;

	no warnings;
	my $base=$size+0; # force to number
	use warnings;
	foreach my $unit (sort keys %units) {
		if ($size=~/[0-9\s]\Q$unit\E$/i) {
			return $base * $units{$unit};
		}
	}
	return $base;
} #}}}

sub humansize ($) { #{{{
	my $size=shift;

	foreach my $unit (reverse sort { $units{$a} &lt;=&gt; $units{$b} || $b cmp $a } keys %units) {
		if ($size / $units{$unit} &gt; 0.25) {
			return (int($size / $units{$unit} * 10)/10).$unit;
		}
	}
	return $size; # near zero, or negative
} #}}}

package IkiWiki::PageSpec;

sub match_maxsize ($$;@) { #{{{
	shift;
	my $maxsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
	if ($@) {
		return IkiWiki::FailReason-&gt;new("unable to parse maxsize (or number too large)");
	}

	my %params=@_;
	if (! exists $params{file}) {
		return IkiWiki::FailReason-&gt;new("no file specified");
	}

	if (-s $params{file} &gt; $maxsize) {
		return IkiWiki::FailReason-&gt;new("file too large (".(-s $params{file})." &gt;  $maxsize)");
	}
	else {
		return IkiWiki::SuccessReason-&gt;new("file not too large");
	}
} #}}}

sub match_minsize ($$;@) { #{{{
	shift;
	my $minsize=eval{IkiWiki::Plugin::attachment::parsesize(shift)};
	if ($@) {
		return IkiWiki::FailReason-&gt;new("unable to parse minsize (or number too large)");
	}

	my %params=@_;
	if (! exists $params{file}) {
		return IkiWiki::FailReason-&gt;new("no file specified");
	}

	if (-s $params{file} &lt; $minsize) {
		return IkiWiki::FailReason-&gt;new("file too small");
	}
	else {
		return IkiWiki::SuccessReason-&gt;new("file not too small");
	}
} #}}}

sub match_mimetype ($$;@) { #{{{
	shift;
	my $wanted=shift;

	my %params=@_;
	if (! exists $params{file}) {
		return IkiWiki::FailReason-&gt;new("no file specified");
	}

	# Use ::magic to get the mime type, the idea is to only trust
	# data obtained by examining the actual file contents.
	eval q{use File::MimeInfo::Magic};
	if ($@) {
		return IkiWiki::FailReason-&gt;new("failed to load File::MimeInfo::Magic ($@); cannot check MIME type");
	}
	my $mimetype=File::MimeInfo::Magic::magic($params{file});
	if (! defined $mimetype) {
		$mimetype="unknown";
	}

	my $regexp=IkiWiki::glob2re($wanted);
	if ($mimetype!~/^$regexp$/i) {
		return IkiWiki::FailReason-&gt;new("file MIME type is $mimetype, not $wanted");
	}
	else {
		return IkiWiki::SuccessReason-&gt;new("file MIME type is $mimetype");
	}
} #}}}

sub match_virusfree ($$;@) { #{{{
	shift;
	my $wanted=shift;

	my %params=@_;
	if (! exists $params{file}) {
		return IkiWiki::FailReason-&gt;new("no file specified");
	}

	if (! exists $IkiWiki::config{virus_checker} ||
	    ! length $IkiWiki::config{virus_checker}) {
		return IkiWiki::FailReason-&gt;new("no virus_checker configured");
	}

	# The file needs to be fed into the virus checker on stdin,
	# because the file is not world-readable, and if clamdscan is
	# used, clamd would fail to read it.
	eval q{use IPC::Open2};
	error($@) if $@;
	open (IN, "&lt;", $params{file}) || return IkiWiki::FailReason-&gt;new("failed to read file");
	binmode(IN);
	my $sigpipe=0;
	$SIG{PIPE} = sub { $sigpipe=1 };
	my $pid=open2(\*CHECKER_OUT, "&lt;&amp;IN", $IkiWiki::config{virus_checker}); 
	my $reason=&lt;CHECKER_OUT&gt;;
	chomp $reason;
	1 while (&lt;CHECKER_OUT&gt;);
	close(CHECKER_OUT);
	waitpid $pid, 0;
	$SIG{PIPE}="DEFAULT";
	if ($sigpipe || $?) {
		if (! length $reason) {
			$reason="virus checker $IkiWiki::config{virus_checker}; failed with no output";
		}
		return IkiWiki::FailReason-&gt;new("file seems to contain a virus ($reason)");
	}
	else {
		return IkiWiki::SuccessReason-&gt;new("file seems virusfree ($reason)");
	}
} #}}}

sub match_ispage ($$;@) { #{{{
	my $filename=shift;

	if (defined IkiWiki::pagetype($filename)) {
		return IkiWiki::SuccessReason-&gt;new("file is a wiki page");
	}
	else {
		return IkiWiki::FailReason-&gt;new("file is not a wiki page");
	}
} #}}}

sub match_user ($$;@) { #{{{
	shift;
	my $user=shift;
	my %params=@_;
	
	if (! exists $params{user}) {
		return IkiWiki::FailReason-&gt;new("no user specified");
	}

	if (defined $params{user} &amp;&amp; lc $params{user} eq lc $user) {
		return IkiWiki::SuccessReason-&gt;new("user is $user");
	}
	elsif (! defined $params{user}) {
		return IkiWiki::FailReason-&gt;new("not logged in");
	}
	else {
		return IkiWiki::FailReason-&gt;new("user is $params{user}, not $user");
	}
} #}}}

sub match_ip ($$;@) { #{{{
	shift;
	my $ip=shift;
	my %params=@_;
	
	if (! exists $params{ip}) {
		return IkiWiki::FailReason-&gt;new("no IP specified");
	}

	if (defined $params{ip} &amp;&amp; lc $params{ip} eq lc $ip) {
		return IkiWiki::SuccessReason-&gt;new("IP is $ip");
	}
	else {
		return IkiWiki::FailReason-&gt;new("IP is $params{ip}, not $ip");
	}
} #}}}

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