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

use warnings;
use strict;
use IkiWiki;
use IkiWiki::UserInfo;
use open qw{:utf8 :std};
use Encode;

sub printheader ($) {
	my $session=shift;
	
	if (($ENV{HTTPS} &amp;&amp; lc $ENV{HTTPS} ne "off") || $config{sslcookie}) {
		print $session-&gt;header(-charset =&gt; 'utf-8',
			-cookie =&gt; $session-&gt;cookie(-httponly =&gt; 1, -secure =&gt; 1));
	}
	else {
		print $session-&gt;header(-charset =&gt; 'utf-8',
			-cookie =&gt; $session-&gt;cookie(-httponly =&gt; 1));
	}
}

sub prepform {
	my $form=shift;
	my $buttons=shift;
	my $session=shift;
	my $cgi=shift;

	if (exists $hooks{formbuilder}) {
		run_hooks(formbuilder =&gt; sub {
			shift-&gt;(form =&gt; $form, cgi =&gt; $cgi, session =&gt; $session,
				buttons =&gt; $buttons);
		});
	}

	return $form;
}

sub showform ($$$$;@) {
	my $form=prepform(@_);
	shift;
	my $buttons=shift;
	my $session=shift;
	my $cgi=shift;

	printheader($session);
	print cgitemplate($cgi, $form-&gt;title,
		$form-&gt;render(submit =&gt; $buttons), @_);
}

sub cgitemplate ($$$;@) {
	my $cgi=shift;
	my $title=shift;
	my $content=shift;
	my %params=@_;
	
	my $template=template("page.tmpl");

	my $page="";
	if (exists $params{page}) {
		$page=delete $params{page};
		$params{forcebaseurl}=urlto($page);
	}
	run_hooks(pagetemplate =&gt; sub {
		shift-&gt;(
			page =&gt; $page,
			destpage =&gt; $page,
			template =&gt; $template,
		);
	});
	templateactions($template, "");

	my $baseurl = baseurl();

	$template-&gt;param(
		dynamic =&gt; 1,
		title =&gt; $title,
		wikiname =&gt; $config{wikiname},
		content =&gt; $content,
		baseurl =&gt; $baseurl,
		html5 =&gt; $config{html5},
		%params,
	);
	
	return $template-&gt;output;
}

sub redirect ($$) {
	my $q=shift;
	eval q{use URI};

	my $topurl = $config{cgiurl};
	if (defined $q &amp;&amp; ! $config{w3mmode} &amp;&amp; ! $config{reverse_proxy}) {
		$topurl = $q-&gt;url;
	}

	my $url=URI-&gt;new(urlabs(shift, $topurl));
	if (! $config{w3mmode}) {
		print $q-&gt;redirect($url);
	}
	else {
		print "Content-type: text/plain\n";
		print "W3m-control: GOTO $url\n\n";
	}
}

sub decode_cgi_utf8 ($) {
	# decode_form_utf8 method is needed for 5.01
	if ($] &lt; 5.01) {
		my $cgi = shift;
		foreach my $f ($cgi-&gt;param) {
			$cgi-&gt;param($f, map { decode_utf8 $_ }
				@{$cgi-&gt;param_fetch($f)});
		}
	}
}

sub safe_decode_utf8 ($) {
    my $octets = shift;
    if (!Encode::is_utf8($octets)) {
        return decode_utf8($octets);
    }
    else {
        return $octets;
    }
}

sub decode_form_utf8 ($) {
	if ($] &gt;= 5.01) {
		my $form = shift;
		foreach my $f ($form-&gt;field) {
			my @value=map { safe_decode_utf8($_) } $form-&gt;field($f);
			$form-&gt;field(name  =&gt; $f,
			             value =&gt; \@value,
		                     force =&gt; 1,
			);
		}
	}
}

# Check if the user is signed in. If not, redirect to the signin form and
# save their place to return to later.
sub needsignin ($$) {
	my $q=shift;
	my $session=shift;

	if (! length $session-&gt;param("name") ||
	    ! userinfo_get($session-&gt;param("name"), "regdate")) {
		$session-&gt;param(postsignin =&gt; $q-&gt;query_string);
		cgi_signin($q, $session);
		cgi_savesession($session);
		exit;
	}
}

sub cgi_signin ($$;$) {
	my $q=shift;
	my $session=shift;
	my $returnhtml=shift;

	decode_cgi_utf8($q);
	eval q{use CGI::FormBuilder};
	error($@) if $@;
	my $form = CGI::FormBuilder-&gt;new(
		title =&gt; "signin",
		name =&gt; "signin",
		charset =&gt; "utf-8",
		method =&gt; 'POST',
		required =&gt; 'NONE',
		javascript =&gt; 0,
		params =&gt; $q,
		action =&gt; cgiurl(),
		header =&gt; 0,
		template =&gt; {type =&gt; 'div'},
		stylesheet =&gt; 1,
	);
	my $buttons=["Login"];
	
	$form-&gt;field(name =&gt; "do", type =&gt; "hidden", value =&gt; "signin",
		force =&gt; 1);
	
	decode_form_utf8($form);
	run_hooks(formbuilder_setup =&gt; sub {
		shift-&gt;(form =&gt; $form, cgi =&gt; $q, session =&gt; $session,
		        buttons =&gt; $buttons);
	});
	decode_form_utf8($form);

	if ($form-&gt;submitted) {
		$form-&gt;validate;
	}

	if ($returnhtml) {
		$form=prepform($form, $buttons, $session, $q);
		return $form-&gt;render(submit =&gt; $buttons);
	}

	showform($form, $buttons, $session, $q);
}

sub cgi_postsignin ($$) {
	my $q=shift;
	my $session=shift;
	
	# Continue with whatever was being done before the signin process.
	if (defined $session-&gt;param("postsignin")) {
		my $postsignin=CGI-&gt;new($session-&gt;param("postsignin"));
		$session-&gt;clear("postsignin");
		cgi($postsignin, $session);
		cgi_savesession($session);
		exit;
	}
	else {
		if ($config{sslcookie} &amp;&amp; ! $q-&gt;https()) {
			error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
		}
		else {
			error(gettext("Login succeeded, but I don't remember why you were logging in, so you'll have to navigate back to whatever you were doing. (This should not normally happen. Perhaps you need to enable cookies?)"));
		}
	}
}

sub cgi_prefs ($$) {
	my $q=shift;
	my $session=shift;

	needsignin($q, $session);
	decode_cgi_utf8($q);
	
	# The session id is stored on the form and checked to
	# guard against CSRF.
	my $sid=$q-&gt;param('sid');
	if (! defined $sid) {
		$q-&gt;delete_all;
	}
	elsif ($sid ne $session-&gt;id) {
		error(gettext("Your login session has expired."));
	}

	eval q{use CGI::FormBuilder};
	error($@) if $@;
	my $form = CGI::FormBuilder-&gt;new(
		title =&gt; "preferences",
		name =&gt; "preferences",
		header =&gt; 0,
		charset =&gt; "utf-8",
		method =&gt; 'POST',
		validate =&gt; {
			email =&gt; 'EMAIL',
		},
		required =&gt; 'NONE',
		javascript =&gt; 0,
		params =&gt; $q,
		action =&gt; cgiurl(),
		template =&gt; {type =&gt; 'div'},
		stylesheet =&gt; 1,
		fieldsets =&gt; [
			[login =&gt; gettext("Login")],
			[preferences =&gt; gettext("Preferences")],
			[admin =&gt; gettext("Admin")]
		],
	);
	my $buttons=["Save Preferences", "Logout", "Cancel"];
	
	decode_form_utf8($form);
	run_hooks(formbuilder_setup =&gt; sub {
		shift-&gt;(form =&gt; $form, cgi =&gt; $q, session =&gt; $session,
		        buttons =&gt; $buttons);
	});
	decode_form_utf8($form);
	
	$form-&gt;field(name =&gt; "do", type =&gt; "hidden", value =&gt; "prefs",
		force =&gt; 1);
	$form-&gt;field(name =&gt; "sid", type =&gt; "hidden", value =&gt; $session-&gt;id,
		force =&gt; 1);
	$form-&gt;field(name =&gt; "email", size =&gt; 50, fieldset =&gt; "preferences");
	
	my $user_name=$session-&gt;param("name");

	if (! $form-&gt;submitted) {
		$form-&gt;field(name =&gt; "email", force =&gt; 1,
			value =&gt; userinfo_get($user_name, "email"));
	}
	
	if ($form-&gt;submitted eq 'Logout') {
		$session-&gt;delete();
		redirect($q, baseurl(undef));
		return;
	}
	elsif ($form-&gt;submitted eq 'Cancel') {
		redirect($q, baseurl(undef));
		return;
	}
	elsif ($form-&gt;submitted eq 'Save Preferences' &amp;&amp; $form-&gt;validate) {
		my $email = $form-&gt;field('email');
		if (defined $email) {
			userinfo_set($user_name, 'email', $email) ||
				error("failed to set email");
		}

		$form-&gt;text(gettext("Preferences saved."));
	}
	
	showform($form, $buttons, $session, $q,
		prefsurl =&gt; "", # avoid showing the preferences link
	);
}

sub cgi_custom_failure ($$$) {
	my $q=shift;
	my $httpstatus=shift;
	my $message=shift;

	print $q-&gt;header(
		-status =&gt; $httpstatus,
		-charset =&gt; 'utf-8',
	);
	print $message;

	# Internet Explod^Hrer won't show custom 404 responses
	# unless they're &gt;= 512 bytes
	print ' ' x 512;

	exit;
}

sub check_banned ($$) {
	my $q=shift;
	my $session=shift;

	my $banned=0;
	my $name=$session-&gt;param("name");
	my $cloak=cloak($name) if defined $name;
	if (defined $name &amp;&amp; 
	    grep { $name eq $_ || $cloak eq $_ } @{$config{banned_users}}) {
		$banned=1;
	}

	foreach my $b (@{$config{banned_users}}) {
		if (pagespec_match("", $b,
			ip =&gt; $session-&gt;remote_addr(),
			name =&gt; defined $name ? $name : "")
		   || pagespec_match("", $b,
		   	ip =&gt; cloak($session-&gt;remote_addr()),
			name =&gt; defined $cloak ? $cloak : "")) {
			$banned=1;
			last;
		}
	}

	if ($banned) {
		$session-&gt;delete();
		cgi_savesession($session);
		cgi_custom_failure(
			$q, "403 Forbidden",
			gettext("You are banned."));
	}
}

sub cgi_getsession ($) {
	my $q=shift;

	eval q{use CGI::Session; use HTML::Entities};
	error($@) if $@;
	CGI::Session-&gt;name("ikiwiki_session_".encode_entities($config{wikiname}));
	
	my $oldmask=umask(077);
	my $session = eval {
		CGI::Session-&gt;new("driver:DB_File", $q,
			{ FileName =&gt; "$config{wikistatedir}/sessions.db" })
	};
	if (! $session || $@) {
		my $error = $@;
		error($error." ".CGI::Session-&gt;errstr());
	}
	
	umask($oldmask);

	return $session;
}

# To guard against CSRF, the user's session id (sid)
# can be stored on a form. This function will check
# (for logged in users) that the sid on the form matches
# the session id in the cookie.
sub checksessionexpiry ($$) {
	my $q=shift;
	my $session = shift;

	if (defined $session-&gt;param("name")) {
		my $sid=$q-&gt;param('sid');
		if (! defined $sid || $sid ne $session-&gt;id || ! length $session-&gt;param("name")) {
			error(gettext("Your login session has expired."));
		}
	}
}

sub cgi_savesession ($) {
	my $session=shift;

	# Force session flush with safe umask.
	my $oldmask=umask(077);
	$session-&gt;flush;
	umask($oldmask);
}

sub cgi (;$$) {
	my $q=shift;
	my $session=shift;

	eval q{use CGI};
	error($@) if $@;
	no warnings "once";
	$CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
	use warnings;

	if (! $q) {
		binmode(STDIN);
		$q=CGI-&gt;new;
		binmode(STDIN, ":utf8");
	
		run_hooks(cgi =&gt; sub { shift-&gt;($q) });
	}

	my $do=$q-&gt;param('do');
	if (! defined $do || ! length $do) {
		my $error = $q-&gt;cgi_error;
		if ($error) {
			error("Request not processed: $error");
		}
		else {
			error("\"do\" parameter missing");
		}
	}

	# Need to lock the wiki before getting a session.
	lockwiki();
	loadindex();
	
	if (! $session) {
		$session=cgi_getsession($q);
	}
	
	# Auth hooks can sign a user in.
	if ($do ne 'signin' &amp;&amp; ! length $session-&gt;param("name")) {
		run_hooks(auth =&gt; sub {
			shift-&gt;($q, $session)
		});
		if (length $session-&gt;param("name")) {
			# Make sure whatever user was authed is in the
			# userinfo db.
			if (! userinfo_get($session-&gt;param("name"), "regdate")) {
				userinfo_setall($session-&gt;param("name"), {
					email =&gt; defined $session-&gt;param("email") ? $session-&gt;param("email") : "",
					password =&gt; "",
					regdate =&gt; time,
				}) || error("failed adding user");
			}
		}
	}
	
	check_banned($q, $session);
	
	run_hooks(sessioncgi =&gt; sub { shift-&gt;($q, $session) });

	if ($do eq 'signin') {
		cgi_signin($q, $session);
		cgi_savesession($session);
	}
	elsif ($do eq 'prefs') {
		cgi_prefs($q, $session);
	}
	elsif (defined $session-&gt;param("postsignin") || $do eq 'postsignin') {
		cgi_postsignin($q, $session);
	}
	else {
		error("unknown do parameter");
	}
}

# Does not need to be called directly; all errors will go through here.
sub cgierror ($) {
	my $message=shift;

	eval q{use HTML::Entities};
	$message = encode_entities($message);

	print "Content-type: text/html\n\n";
	print cgitemplate(undef, gettext("Error"),
		"&lt;p class=\"error\"&gt;".gettext("Error").": $message&lt;/p&gt;");

	die $message;
}

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