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

use warnings;
use strict;
use Encode;
use IkiWiki 2.00;
use URI;

my %knownfeeds;
my %page_numfeeds;
my @inline;
my $nested=0;

sub import { #{{{
	hook(type =&gt; "getopt", id =&gt; "inline", call =&gt; \&amp;getopt);
	hook(type =&gt; "getsetup", id =&gt; "inline", call =&gt; \&amp;getsetup);
	hook(type =&gt; "checkconfig", id =&gt; "inline", call =&gt; \&amp;checkconfig);
	hook(type =&gt; "sessioncgi", id =&gt; "inline", call =&gt; \&amp;sessioncgi);
	hook(type =&gt; "preprocess", id =&gt; "inline", 
		call =&gt; \&amp;IkiWiki::preprocess_inline);
	hook(type =&gt; "pagetemplate", id =&gt; "inline",
		call =&gt; \&amp;IkiWiki::pagetemplate_inline);
	hook(type =&gt; "format", id =&gt; "inline", call =&gt; \&amp;format);
	# Hook to change to do pinging since it's called late.
	# This ensures each page only pings once and prevents slow
	# pings interrupting page builds.
	hook(type =&gt; "change", id =&gt; "inline", call =&gt; \&amp;IkiWiki::pingurl);
} # }}}

sub getopt () { #{{{
	eval q{use Getopt::Long};
	error($@) if $@;
	Getopt::Long::Configure('pass_through');
	GetOptions(
		"rss!" =&gt; \$config{rss},
		"atom!" =&gt; \$config{atom},
		"allowrss!" =&gt; \$config{allowrss},
		"allowatom!" =&gt; \$config{allowatom},
		"pingurl=s" =&gt; sub {
			push @{$config{pingurl}}, $_[1];
		},      
	);
} #}}}

sub getsetup () { #{{{
	return
		plugin =&gt; {
			safe =&gt; 1,
			rebuild =&gt; undef,
		},
		rss =&gt; {
			type =&gt; "boolean",
			example =&gt; 0,
			description =&gt; "enable rss feeds by default?",
			safe =&gt; 1,
			rebuild =&gt; 1,
		},
		atom =&gt; {
			type =&gt; "boolean",
			example =&gt; 0,
			description =&gt; "enable atom feeds by default?",
			safe =&gt; 1,
			rebuild =&gt; 1,
		},
		allowrss =&gt; {
			type =&gt; "boolean",
			example =&gt; 0,
			description =&gt; "allow rss feeds to be used?",
			safe =&gt; 1,
			rebuild =&gt; 1,
		},
		allowatom =&gt; {
			type =&gt; "boolean",
			example =&gt; 0,
			description =&gt; "allow atom feeds to be used?",
			safe =&gt; 1,
			rebuild =&gt; 1,
		},
		pingurl =&gt; {
			type =&gt; "string",
			example =&gt; "http://rpc.technorati.com/rpc/ping",
			description =&gt; "urls to ping (using XML-RPC) on feed update",
			safe =&gt; 1,
			rebuild =&gt; 0,
		},
} #}}}

sub checkconfig () { #{{{
	if (($config{rss} || $config{atom}) &amp;&amp; ! length $config{url}) {
		error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
	}
	if ($config{rss}) {
		push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
	}
	if ($config{atom}) {
		push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
	}
	if (! exists $config{pingurl}) {
		$config{pingurl}=[];
	}
} #}}}

sub format (@) { #{{{
        my %params=@_;

	# Fill in the inline content generated earlier. This is actually an
	# optimisation.
	$params{content}=~s{&lt;div class="inline" id="([^"]+)"&gt;&lt;/div&gt;}{
		delete @inline[$1,]
	}eg;
	return $params{content};
} #}}}

sub sessioncgi ($$) { #{{{
	my $q=shift;
	my $session=shift;

	if ($q-&gt;param('do') eq 'blog') {
		my $page=titlepage(decode_utf8($q-&gt;param('title')));
		$page=~s/(\/)/"__".ord($1)."__"/eg; # don't create subdirs
		# if the page already exists, munge it to be unique
		my $from=$q-&gt;param('from');
		my $add="";
		while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
			$add=1 unless length $add;
			$add++;
		}
		$q-&gt;param('page', $page.$add);
		# now go create the page
		$q-&gt;param('do', 'create');
		# make sure the editpage plugin in loaded
		if (IkiWiki-&gt;can("cgi_editpage")) {
			IkiWiki::cgi_editpage($q, $session);
		}
		else {
			error(gettext("page editing not allowed"));
		}
		exit;
	}
}

# Back to ikiwiki namespace for the rest, this code is very much
# internal to ikiwiki even though it's separated into a plugin.
package IkiWiki;

my %toping;
my %feedlinks;

sub preprocess_inline (@) { #{{{
	my %params=@_;
	
	if (! exists $params{pages}) {
		error gettext("missing pages parameter");
	}
	my $raw=yesno($params{raw});
	my $archive=yesno($params{archive});
	my $rss=(($config{rss} || $config{allowrss}) &amp;&amp; exists $params{rss}) ? yesno($params{rss}) : $config{rss};
	my $atom=(($config{atom} || $config{allowatom}) &amp;&amp; exists $params{atom}) ? yesno($params{atom}) : $config{atom};
	my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
	my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
	my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
	my $feedonly=yesno($params{feedonly});
	if (! exists $params{show} &amp;&amp; ! $archive) {
		$params{show}=10;
	}
	if (! exists $params{feedshow} &amp;&amp; exists $params{show}) {
		$params{feedshow}=$params{show};
	}
	my $desc;
	if (exists $params{description}) {
		$desc = $params{description} 
	}
	else {
		$desc = $config{wikiname};
	}
	my $actions=yesno($params{actions});
	if (exists $params{template}) {
		$params{template}=~s/[^-_a-zA-Z0-9]+//g;
	}
	else {
		$params{template} = $archive ? "archivepage" : "inlinepage";
	}

	my @list;
	foreach my $page (keys %pagesources) {
		next if $page eq $params{page};
		if (pagespec_match($page, $params{pages}, location =&gt; $params{page})) {
			push @list, $page;
		}
	}

	if (exists $params{sort} &amp;&amp; $params{sort} eq 'title') {
		@list=sort { pagetitle(basename($a)) cmp pagetitle(basename($b)) } @list;
	}
	elsif (exists $params{sort} &amp;&amp; $params{sort} eq 'mtime') {
		@list=sort { $pagemtime{$b} &lt;=&gt; $pagemtime{$a} } @list;
	}
	elsif (! exists $params{sort} || $params{sort} eq 'age') {
		@list=sort { $pagectime{$b} &lt;=&gt; $pagectime{$a} } @list;
	}
	else {
		error sprintf(gettext("unknown sort type %s"), $params{sort});
	}

	if (yesno($params{reverse})) {
		@list=reverse(@list);
	}

	if (exists $params{skip}) {
		@list=@list[$params{skip} .. scalar @list - 1];
	}
	
	my @feedlist;
	if ($feeds) {
		if (exists $params{feedshow} &amp;&amp;
		    $params{feedshow} &amp;&amp; @list &gt; $params{feedshow}) {
			@feedlist=@list[0..$params{feedshow} - 1];
		}
		else {
			@feedlist=@list;
		}
	}
	
	if ($params{show} &amp;&amp; @list &gt; $params{show}) {
		@list=@list[0..$params{show} - 1];
	}

	add_depends($params{page}, $params{pages});
	# Explicitly add all currently displayed pages as dependencies, so
	# that if they are removed or otherwise changed, the inline will be
	# sure to be updated.
	add_depends($params{page}, join(" or ", $#list &gt;= $#feedlist ? @list : @feedlist));
	
	if ($feeds &amp;&amp; exists $params{feedpages}) {
		@feedlist=grep { pagespec_match($_, $params{feedpages}, location =&gt; $params{page}) } @feedlist;
	}

	my ($feedbase, $feednum);
	if ($feeds) {
		# Ensure that multiple feeds on a page go to unique files.
		
		# Feedfile can lead to conflicts if usedirs is not enabled,
		# so avoid supporting it in that case.
		delete $params{feedfile} if ! $config{usedirs};
		# Tight limits on legal feedfiles, to avoid security issues
		# and conflicts.
		if (defined $params{feedfile}) {
			if ($params{feedfile} =~ /\// ||
			    $params{feedfile} !~ /$config{wiki_file_regexp}/) {
				error("illegal feedfile");
			}
			$params{feedfile}=possibly_foolish_untaint($params{feedfile});
		}
		$feedbase=targetpage($params{destpage}, "", $params{feedfile});

		my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
		if (exists $knownfeeds{$feedid}) {
			$feednum=$knownfeeds{$feedid};
		}
		else {
			if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
				if ($feeds) {
					$feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
				}
			}
			else {
				$feednum=$knownfeeds{$feedid}="";
				if ($feeds) {
					$page_numfeeds{$params{destpage}}{$feedbase}=1;
				}
			}
		}
	}

	my $rssurl=basename($feedbase."rss".$feednum) if $feeds &amp;&amp; $rss;
	my $atomurl=basename($feedbase."atom".$feednum) if $feeds &amp;&amp; $atom;

	my $ret="";

	if (length $config{cgiurl} &amp;&amp; ! $params{preview} &amp;&amp; (exists $params{rootpage} ||
	    (exists $params{postform} &amp;&amp; yesno($params{postform}))) &amp;&amp;
	    IkiWiki-&gt;can("cgi_editpage")) {
		# Add a blog post form, with feed buttons.
		my $formtemplate=template("blogpost.tmpl", blind_cache =&gt; 1);
		$formtemplate-&gt;param(cgiurl =&gt; $config{cgiurl});
		my $rootpage;
		if (exists $params{rootpage}) {
			$rootpage=bestlink($params{page}, $params{rootpage});
			if (!length $rootpage) {
				$rootpage=$params{rootpage};
			}
		}
		else {
			$rootpage=$params{page};
		}
		$formtemplate-&gt;param(rootpage =&gt; $rootpage);
		$formtemplate-&gt;param(rssurl =&gt; $rssurl) if $feeds &amp;&amp; $rss;
		$formtemplate-&gt;param(atomurl =&gt; $atomurl) if $feeds &amp;&amp; $atom;
		if (exists $params{postformtext}) {
			$formtemplate-&gt;param(postformtext =&gt;
				$params{postformtext});
		}
		else {
			$formtemplate-&gt;param(postformtext =&gt;
				gettext("Add a new post titled:"));
		}
		$ret.=$formtemplate-&gt;output;
	    	
		# The post form includes the feed buttons, so
		# emptyfeeds cannot be hidden.
		$emptyfeeds=1;
	}
	elsif ($feeds &amp;&amp; !$params{preview} &amp;&amp; ($emptyfeeds || @feedlist)) {
		# Add feed buttons.
		my $linktemplate=template("feedlink.tmpl", blind_cache =&gt; 1);
		$linktemplate-&gt;param(rssurl =&gt; $rssurl) if $rss;
		$linktemplate-&gt;param(atomurl =&gt; $atomurl) if $atom;
		$ret.=$linktemplate-&gt;output;
	}
	
	if (! $feedonly) {
		require HTML::Template;
		my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache =&gt; 1);
		if (! @params) {
			error sprintf(gettext("nonexistant template %s"), $params{template});
		}
		my $template=HTML::Template-&gt;new(@params) unless $raw;
	
		foreach my $page (@list) {
			my $file = $pagesources{$page};
			my $type = pagetype($file);
			if (! $raw || ($raw &amp;&amp; ! defined $type)) {
				unless ($archive &amp;&amp; $quick) {
					# Get the content before populating the
					# template, since getting the content uses
					# the same template if inlines are nested.
					my $content=get_inline_content($page, $params{destpage});
					$template-&gt;param(content =&gt; $content);
				}
				$template-&gt;param(pageurl =&gt; urlto(bestlink($params{page}, $page), $params{destpage}));
				$template-&gt;param(title =&gt; pagetitle(basename($page)));
				$template-&gt;param(ctime =&gt; displaytime($pagectime{$page}, $params{timeformat}));
				$template-&gt;param(mtime =&gt; displaytime($pagemtime{$page}, $params{timeformat}));
				$template-&gt;param(first =&gt; 1) if $page eq $list[0];
				$template-&gt;param(last =&gt; 1) if $page eq $list[$#list];
	
				if ($actions) {
					my $file = $pagesources{$page};
					my $type = pagetype($file);
					if ($config{discussion}) {
						my $discussionlink=gettext("discussion");
						if ($page !~ /.*\/\Q$discussionlink\E$/ &amp;&amp;
						    (length $config{cgiurl} ||
						     exists $links{$page."/".$discussionlink})) {
							$template-&gt;param(have_actions =&gt; 1);
							$template-&gt;param(discussionlink =&gt;
								htmllink($page,
									$params{destpage},
									gettext("Discussion"),
									noimageinline =&gt; 1,
									forcesubpage =&gt; 1));
						}
					}
					if (length $config{cgiurl} &amp;&amp; defined $type) {
						$template-&gt;param(have_actions =&gt; 1);
						$template-&gt;param(editurl =&gt; cgiurl(do =&gt; "edit", page =&gt; $page));
					}
				}
	
				run_hooks(pagetemplate =&gt; sub {
					shift-&gt;(page =&gt; $page, destpage =&gt; $params{destpage},
						template =&gt; $template,);
				});
	
				$ret.=$template-&gt;output;
				$template-&gt;clear_params;
			}
			else {
				if (defined $type) {
					$ret.="\n".
					      linkify($page, $params{destpage},
					      preprocess($page, $params{destpage},
					      filter($page, $params{destpage},
					      readfile(srcfile($file)))));
				}
			}
		}
	}
	
	if ($feeds &amp;&amp; ($emptyfeeds || @feedlist)) {
		if ($rss) {
			my $rssp=$feedbase."rss".$feednum;
			will_render($params{destpage}, $rssp);
			if (! $params{preview}) {
				writefile($rssp, $config{destdir},
					genfeed("rss",
						$config{url}."/".$rssp, $desc, $params{guid}, $params{destpage}, @feedlist));
				$toping{$params{destpage}}=1 unless $config{rebuild};
				$feedlinks{$params{destpage}}.=qq{&lt;link rel="alternate" type="application/rss+xml" title="$desc (RSS)" href="$rssurl" /&gt;};
			}
		}
		if ($atom) {
			my $atomp=$feedbase."atom".$feednum;
			will_render($params{destpage}, $atomp);
			if (! $params{preview}) {
				writefile($atomp, $config{destdir},
					genfeed("atom", $config{url}."/".$atomp, $desc, $params{guid}, $params{destpage}, @feedlist));
				$toping{$params{destpage}}=1 unless $config{rebuild};
				$feedlinks{$params{destpage}}.=qq{&lt;link rel="alternate" type="application/atom+xml" title="$desc (Atom)" href="$atomurl" /&gt;};
			}
		}
	}
	
	return $ret if $raw || $nested;
	push @inline, $ret;
	return "&lt;div class=\"inline\" id=\"$#inline\"&gt;&lt;/div&gt;\n\n";
} #}}}

sub pagetemplate_inline (@) { #{{{
	my %params=@_;
	my $page=$params{page};
	my $template=$params{template};

	$template-&gt;param(feedlinks =&gt; $feedlinks{$page})
		if exists $feedlinks{$page} &amp;&amp; $template-&gt;query(name =&gt; "feedlinks");
} #}}}

sub get_inline_content ($$) { #{{{
	my $page=shift;
	my $destpage=shift;
	
	my $file=$pagesources{$page};
	my $type=pagetype($file);
	if (defined $type) {
		$nested++;
		my $ret=htmlize($page, $destpage, $type,
		       linkify($page, $destpage,
		       preprocess($page, $destpage,
		       filter($page, $destpage,
		       readfile(srcfile($file))))));
		$nested--;
		return $ret;
	}
	else {
		return "";
	}
} #}}}

sub date_822 ($) { #{{{
	my $time=shift;

	my $lc_time=POSIX::setlocale(&amp;POSIX::LC_TIME);
	POSIX::setlocale(&amp;POSIX::LC_TIME, "C");
	my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
	POSIX::setlocale(&amp;POSIX::LC_TIME, $lc_time);
	return $ret;
} #}}}

sub date_3339 ($) { #{{{
	my $time=shift;

	my $lc_time=POSIX::setlocale(&amp;POSIX::LC_TIME);
	POSIX::setlocale(&amp;POSIX::LC_TIME, "C");
	my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
	POSIX::setlocale(&amp;POSIX::LC_TIME, $lc_time);
	return $ret;
} #}}}

sub absolute_urls ($$) { #{{{
	# sucky sub because rss sucks
	my $content=shift;
	my $baseurl=shift;

	my $url=$baseurl;
	$url=~s/[^\/]+$//;

        # what is the non path part of the url?
        my $top_uri = URI-&gt;new($url);
        $top_uri-&gt;path_query(""); # reset the path
        my $urltop = $top_uri-&gt;as_string;

	$content=~s/(&lt;a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
        # relative to another wiki page
	$content=~s/(&lt;a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)([^\/][^"]*)"/$1 href="$url$2"/mig;
	$content=~s/(&lt;img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)([^\/][^"]*)"/$1 src="$url$2"/mig;
        # relative to the top of the site
	$content=~s/(&lt;a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)(\/[^"]*)"/$1 href="$urltop$2"/mig;
	$content=~s/(&lt;img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)(\/[^"]*)"/$1 src="$urltop$2"/mig;
	return $content;
} #}}}

sub genfeed ($$$$$@) { #{{{
	my $feedtype=shift;
	my $feedurl=shift;
	my $feeddesc=shift;
	my $guid=shift;
	my $page=shift;
	my @pages=@_;
	
	my $url=URI-&gt;new(encode_utf8(urlto($page,"",1)));
	
	my $itemtemplate=template($feedtype."item.tmpl", blind_cache =&gt; 1);
	my $content="";
	my $lasttime = 0;
	foreach my $p (@pages) {
		my $u=URI-&gt;new(encode_utf8(urlto($p, "", 1)));
		my $pcontent = absolute_urls(get_inline_content($p, $page), $url);

		$itemtemplate-&gt;param(
			title =&gt; pagetitle(basename($p)),
			url =&gt; $u,
			permalink =&gt; $u,
			cdate_822 =&gt; date_822($pagectime{$p}),
			mdate_822 =&gt; date_822($pagemtime{$p}),
			cdate_3339 =&gt; date_3339($pagectime{$p}),
			mdate_3339 =&gt; date_3339($pagemtime{$p}),
		);

		if (exists $pagestate{$p} &amp;&amp;
		    exists $pagestate{$p}{meta}{guid}) {
			$itemtemplate-&gt;param(guid =&gt; $pagestate{$p}{meta}{guid});
		}

		if ($itemtemplate-&gt;query(name =&gt; "enclosure")) {
			my $file=$pagesources{$p};
			my $type=pagetype($file);
			if (defined $type) {
				$itemtemplate-&gt;param(content =&gt; $pcontent);
			}
			else {
				my $size=(srcfile_stat($file))[8];
				my $mime="unknown";
				eval q{use File::MimeInfo};
				if (! $@) {
					$mime = mimetype($file);
				}
				$itemtemplate-&gt;param(
					enclosure =&gt; $u,
					type =&gt; $mime,
					length =&gt; $size,
				);
			}
		}
		else {
			$itemtemplate-&gt;param(content =&gt; $pcontent);
		}

		run_hooks(pagetemplate =&gt; sub {
			shift-&gt;(page =&gt; $p, destpage =&gt; $page,
				template =&gt; $itemtemplate);
		});

		$content.=$itemtemplate-&gt;output;
		$itemtemplate-&gt;clear_params;

		$lasttime = $pagemtime{$p} if $pagemtime{$p} &gt; $lasttime;
	}

	my $template=template($feedtype."page.tmpl", blind_cache =&gt; 1);
	$template-&gt;param(
		title =&gt; $page ne "index" ? pagetitle($page) : $config{wikiname},
		wikiname =&gt; $config{wikiname},
		pageurl =&gt; $url,
		content =&gt; $content,
		feeddesc =&gt; $feeddesc,
		guid =&gt; $guid,
		feeddate =&gt; date_3339($lasttime),
		feedurl =&gt; $feedurl,
		version =&gt; $IkiWiki::version,
	);
	run_hooks(pagetemplate =&gt; sub {
		shift-&gt;(page =&gt; $page, destpage =&gt; $page,
			template =&gt; $template);
	});
	
	return $template-&gt;output;
} #}}}

sub pingurl (@) { #{{{
	return unless @{$config{pingurl}} &amp;&amp; %toping;

	eval q{require RPC::XML::Client};
	if ($@) {
		debug(gettext("RPC::XML::Client not found, not pinging"));
		return;
	}

	# daemonize here so slow pings don't slow down wiki updates
	defined(my $pid = fork) or error("Can't fork: $!");
	return if $pid;
	chdir '/';
	POSIX::setsid() or error("Can't start a new session: $!");
	open STDIN, '/dev/null';
	open STDOUT, '&gt;/dev/null';
	open STDERR, '&gt;&amp;STDOUT' or error("Can't dup stdout: $!");

	# Don't need to keep a lock on the wiki as a daemon.
	IkiWiki::unlockwiki();

	foreach my $page (keys %toping) {
		my $title=pagetitle(basename($page), 0);
		my $url=urlto($page, "", 1);
		foreach my $pingurl (@{$config{pingurl}}) {
			debug("Pinging $pingurl for $page");
			eval {
				my $client = RPC::XML::Client-&gt;new($pingurl);
				my $req = RPC::XML::request-&gt;new('weblogUpdates.ping',
					$title, $url);
				my $res = $client-&gt;send_request($req);
				if (! ref $res) {
					error("Did not receive response to ping");
				}
				my $r=$res-&gt;value;
				if (! exists $r-&gt;{flerror} || $r-&gt;{flerror}) {
					error("Ping rejected: ".(exists $r-&gt;{message} ? $r-&gt;{message} : "[unknown reason]"));
				}
			};
			if ($@) {
				error "Ping failed: $@";
			}
		}
	}

	exit 0; # daemon done
} #}}}

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