2 # Page inlining and blogging.
3 package IkiWiki::Plugin::inline;
17 hook(type => "getopt", id => "inline", call => \&getopt);
18 hook(type => "getsetup", id => "inline", call => \&getsetup);
19 hook(type => "checkconfig", id => "inline", call => \&checkconfig);
20 hook(type => "sessioncgi", id => "inline", call => \&sessioncgi);
21 hook(type => "preprocess", id => "inline",
22 call => \&IkiWiki::preprocess_inline, scan => 1);
23 hook(type => "pagetemplate", id => "inline",
24 call => \&IkiWiki::pagetemplate_inline);
25 hook(type => "format", id => "inline", call => \&format, first => 1);
26 # Hook to change to do pinging since it's called late.
27 # This ensures each page only pings once and prevents slow
28 # pings interrupting page builds.
29 hook(type => "rendered", id => "inline", call => \&IkiWiki::pingurl);
33 eval q{use Getopt::Long};
35 Getopt::Long::Configure('pass_through');
37 "rss!" => \$config{rss},
38 "atom!" => \$config{atom},
39 "allowrss!" => \$config{allowrss},
40 "allowatom!" => \$config{allowatom},
42 push @{$config{pingurl}}, $_[1];
57 description => "enable rss feeds by default?",
64 description => "enable atom feeds by default?",
71 description => "allow rss feeds to be used?",
78 description => "allow atom feeds to be used?",
84 example => "http://rpc.technorati.com/rpc/ping",
85 description => "urls to ping (using XML-RPC) on feed update",
92 if (($config{rss} || $config{atom}) && ! length $config{url}) {
93 error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
96 push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
99 push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
101 if (! exists $config{pingurl}) {
109 # Fill in the inline content generated earlier. This is actually an
111 $params{content}=~s{<div class="inline" id="([^"]+)"></div>}{
114 return $params{content};
117 sub sessioncgi ($$) {
121 if ($q->param('do') eq 'blog') {
122 my $page=titlepage(decode_utf8(scalar $q->param('title')));
123 $page=~s/(\/)/"__".ord($1)."__"/eg; # don't create subdirs
124 # if the page already exists, munge it to be unique
125 my $from=$q->param('from');
127 while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
128 $add=1 unless length $add;
131 $q->param('page', "/$from/$page$add");
132 # now go create the page
133 $q->param('do', 'create');
134 # make sure the editpage plugin is loaded
135 if (IkiWiki->can("cgi_editpage")) {
136 IkiWiki::cgi_editpage($q, $session);
139 error(gettext("page editing not allowed"));
145 # Back to ikiwiki namespace for the rest, this code is very much
146 # internal to ikiwiki even though it's separated into a plugin.
152 sub preprocess_inline (@) {
155 if (! exists $params{pages} && ! exists $params{pagenames}) {
156 error gettext("missing pages parameter");
159 if (! defined wantarray) {
160 # Running in scan mode: only do the essentials
162 if (yesno($params{trail}) && IkiWiki::Plugin::trail->can("preprocess_trailitems")) {
163 # default to sorting by age with fallback to title,
164 # the same as inline itself, but let the params
166 IkiWiki::Plugin::trail::preprocess_trailitems(sort => 'age title', %params);
172 if (yesno($params{trail}) && IkiWiki::Plugin::trail->can("preprocess_trailitems")) {
173 scalar IkiWiki::Plugin::trail::preprocess_trailitems(sort => 'age title', %params);
176 my $raw=yesno($params{raw});
177 my $archive=yesno($params{archive});
178 my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
179 my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
180 my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
181 my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick && ! $raw;
182 my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
183 my $feedonly=yesno($params{feedonly});
185 # Backwards compatibility
186 if (defined $params{show} && $params{show} =~ m/^-?\d+$/) {
187 $params{limit} = $params{show};
188 delete $params{show};
190 if (defined $params{feedshow} && $params{feedshow} =~ m/^\d+$/) {
191 $params{feedlimit} = $params{feedshow};
192 delete $params{feedshow};
195 if (! exists $params{limit} && ! $archive) {
198 if (! exists $params{feedlimit} && exists $params{limit}) {
199 $params{feedlimit}=$params{limit};
202 if (exists $params{title}) {
203 $title = $params{title};
206 $title = $params{page} ne "index" ? pagetitle($params{page}) : $config{wikiname};
209 if (exists $params{description}) {
210 $desc = $params{description}
213 $desc = $config{wikiname};
215 my $actions=yesno($params{actions});
216 if (exists $params{template}) {
217 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
220 $params{template} = $archive ? "archivepage" : "inlinepage";
225 if (exists $params{pagenames}) {
226 foreach my $p (qw(sort pages)) {
227 if (exists $params{$p}) {
228 error sprintf(gettext("the %s and %s parameters cannot be used together"),
233 @list = split ' ', $params{pagenames};
235 if (yesno($params{reverse})) {
236 @list=reverse(@list);
239 foreach my $p (@list) {
240 add_depends($params{page}, $p, deptype($quick ? "presence" : "content"));
243 @list = grep { exists $pagesources{$_} } @list;
247 if ($params{limit}) {
250 if ($params{feedlimit} && $num < $params{feedlimit} && $num > 0) {
251 $num=$params{feedlimit};
253 if ($params{skip} && $num) {
257 @list = pagespec_match_list($params{page}, $params{pages},
258 deptype => deptype($quick ? "presence" : "content"),
259 filter => sub { $_[0] eq $params{page} },
260 sort => exists $params{sort} ? $params{sort} : "age title",
261 reverse => yesno($params{reverse}),
262 ($num ? (num => $num) : ()),
266 if (exists $params{skip}) {
267 @list=@list[$params{skip} .. $#list];
272 if (exists $params{feedlimit} &&
273 $params{feedlimit} && @list > $params{feedlimit}) {
274 @feedlist=@list[0..$params{feedlimit} - 1];
281 if ($params{limit} && @list > $params{limit}) {
282 @list=@list[0..$params{limit} - 1];
285 if ($feeds && exists $params{feedpages}) {
286 @feedlist = pagespec_match_list(
287 $params{page}, "($params{pages}) and ($params{feedpages})",
288 deptype => deptype($quick ? "presence" : "content"),
293 my ($feedbase, $feednum);
295 # Ensure that multiple feeds on a page go to unique files.
297 # Feedfile can lead to conflicts if usedirs is not enabled,
298 # so avoid supporting it in that case.
299 delete $params{feedfile} if ! $config{usedirs};
300 # Tight limits on legal feedfiles, to avoid security issues
302 if (defined $params{feedfile}) {
303 if ($params{feedfile} =~ /\// ||
304 $params{feedfile} !~ /$config{wiki_file_regexp}/) {
305 error("illegal feedfile");
307 $params{feedfile}=possibly_foolish_untaint($params{feedfile});
309 $feedbase=targetpage($params{page}, "", $params{feedfile});
311 my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
312 if (exists $knownfeeds{$feedid}) {
313 $feednum=$knownfeeds{$feedid};
316 if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
318 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
322 $feednum=$knownfeeds{$feedid}="";
324 $page_numfeeds{$params{destpage}}{$feedbase}=1;
330 my ($rssurl, $atomurl, $rssdesc, $atomdesc);
333 $rssurl=abs2rel($feedbase."rss".$feednum, dirname(htmlpage($params{destpage})));
334 $rssdesc = sprintf(gettext("%s (RSS feed)"), $desc);
337 $atomurl=abs2rel($feedbase."atom".$feednum, dirname(htmlpage($params{destpage})));
338 $atomdesc = sprintf(gettext("%s (Atom feed)"), $desc);
344 my $postform = (exists $params{rootpage});
345 if (exists $params{postform}) {
346 $postform = yesno($params{postform});
349 if (length $config{cgiurl} && ! $params{preview} && $postform &&
350 IkiWiki->can("cgi_editpage")) {
351 # Add a blog post form, with feed buttons.
352 my $formtemplate=template_depends("blogpost.tmpl", $params{page}, blind_cache => 1);
353 $formtemplate->param(cgiurl => IkiWiki::cgiurl());
354 $formtemplate->param(rootpage => rootpage(%params));
357 $formtemplate->param(rssurl => $rssurl);
358 $formtemplate->param(rssdesc => $rssdesc);
361 $formtemplate->param(atomurl => $atomurl);
362 $formtemplate->param(atomdesc => $atomdesc);
365 if (exists $params{postformtext}) {
366 $formtemplate->param(postformtext =>
367 $params{postformtext});
370 $formtemplate->param(postformtext =>
371 gettext("Add a new post titled:"));
373 if (exists $params{id}) {
374 $formtemplate->param(postformid =>
377 $ret.=$formtemplate->output;
379 # The post form includes the feed buttons, so
380 # emptyfeeds cannot be hidden.
383 elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
385 my $linktemplate=template_depends("feedlink.tmpl", $params{page}, blind_cache => 1);
387 $linktemplate->param(rssurl => $rssurl);
388 $linktemplate->param(rssdesc => $rssdesc);
391 $linktemplate->param(atomurl => $atomurl);
392 $linktemplate->param(atomdesc => $atomdesc);
394 if (exists $params{id}) {
395 $linktemplate->param(id => $params{id});
397 $ret.=$linktemplate->output;
403 # cannot use wiki pages as templates; template not sanitized due to
406 $template=template_depends($params{template}.".tmpl", $params{page},
410 # gettext can clobber $@
412 error sprintf(gettext("failed to process template %s"), $params{template}.".tmpl").": $error";
415 my $needcontent=$raw || (!($archive && $quick) && $template->query(name => 'content'));
417 foreach my $page (@list) {
418 my $file = $pagesources{$page};
419 my $type = pagetype($file);
422 # Get the content before populating the
423 # template, since getting the content uses
424 # the same template if inlines are nested.
425 my $content=get_inline_content($page, $params{destpage});
426 $template->param(content => $content);
428 $template->param(pageurl => urlto($page, $params{destpage}));
429 $template->param(inlinepage => $page);
430 $template->param(title => pagetitle(basename($page)));
431 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}, 1));
432 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
433 $template->param(first => 1) if $page eq $list[0];
434 $template->param(last => 1) if $page eq $list[$#list];
435 $template->param(html5 => $config{html5});
438 my $file = $pagesources{$page};
439 my $type = pagetype($file);
440 if ($config{discussion}) {
441 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
442 (length $config{cgiurl} ||
443 exists $pagesources{$page."/".lc($config{discussionpage})})) {
444 $template->param(have_actions => 1);
445 $template->param(discussionlink =>
448 $config{discussionpage},
453 if (length $config{cgiurl} &&
455 IkiWiki->can("cgi_editpage")) {
456 $template->param(have_actions => 1);
457 $template->param(editurl => cgiurl(do => "edit", page => $page));
462 run_hooks(pagetemplate => sub {
463 shift->(page => $page, destpage => $params{destpage},
464 template => $template,);
467 $ret.=$template->output;
468 $template->clear_params;
473 linkify($page, $params{destpage},
474 preprocess($page, $params{destpage},
475 filter($page, $params{destpage},
476 readfile(srcfile($file)))));
480 readfile(srcfile($file));
486 if ($feeds && ($emptyfeeds || @feedlist)) {
488 my $rssp=$feedbase."rss".$feednum;
489 will_render($params{destpage}, $rssp);
490 if (! $params{preview}) {
491 writefile($rssp, $config{destdir},
493 $config{url}."/".$rssp, $title, $desc, $params{guid}, $params{page}, @feedlist));
494 $toping{$params{destpage}}=1 unless $config{rebuild};
495 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$rssdesc" href="$rssurl" />};
499 my $atomp=$feedbase."atom".$feednum;
500 will_render($params{destpage}, $atomp);
501 if (! $params{preview}) {
502 writefile($atomp, $config{destdir},
503 genfeed("atom", $config{url}."/".$atomp, $title, $desc, $params{guid}, $params{page}, @feedlist));
504 $toping{$params{destpage}}=1 unless $config{rebuild};
505 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$atomdesc" href="$atomurl" />};
510 clear_inline_content_cache();
512 return $ret if $raw || $nested;
514 return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
517 sub pagetemplate_inline (@) {
519 my $page=$params{page};
520 my $template=$params{template};
522 $template->param(feedlinks => $feedlinks{$page})
523 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
528 my $cached_destpage="";
530 sub get_inline_content ($$) {
534 if (exists $inline_content{$page} && $cached_destpage eq $destpage) {
535 return $inline_content{$page};
538 my $file=$pagesources{$page};
539 my $type=pagetype($file);
543 $ret=htmlize($page, $destpage, $type,
544 linkify($page, $destpage,
545 preprocess($page, $destpage,
546 filter($page, $destpage,
547 readfile(srcfile($file))))));
549 if (isinternal($page)) {
550 # make inlined text of internal pages searchable
551 run_hooks(indexhtml => sub {
552 shift->(page => $page, destpage => $destpage,
558 if ($cached_destpage ne $destpage) {
559 clear_inline_content_cache();
560 $cached_destpage=$destpage;
562 return $inline_content{$page}=$ret;
565 sub clear_inline_content_cache () {
574 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
575 POSIX::setlocale(&POSIX::LC_TIME, "C");
576 my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
577 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
581 sub absolute_urls ($$) {
582 # needed because rss sucks
588 my $urltop; # calculated if needed
592 eval q{use HTML::Parser; use HTML::Tagset};
594 my $p = HTML::Parser->new(api_version => 3);
595 $p->handler(default => sub { $ret.=join("", @_) }, "text");
596 $p->handler(start => sub {
597 my ($tagname, $pos, $text) = @_;
598 if (ref $HTML::Tagset::linkElements{$tagname}) {
600 # use attribute sets from right to left
601 # to avoid invalidating the offsets
602 # when replacing the values
603 my ($k_offset, $k_len, $v_offset, $v_len) =
605 my $attrname = lc(substr($text, $k_offset, $k_len));
606 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
607 next unless $v_offset; # 0 v_offset means no value
608 my $v = substr($text, $v_offset, $v_len);
609 $v =~ s/^([\'\"])(.*)\1$/$2/;
610 eval q{use HTML::Entities};
611 my $dv = decode_entities($v);
613 $v=$baseurl.$v; # anchor
615 elsif ($dv=~/^(?!\w+:)[^\/]/) {
616 $v=URI->new_abs($v, $url)->canonical; # relative url
619 if (! defined $urltop) {
620 # what is the non path part of the url?
621 my $top_uri = URI->new($url);
622 $top_uri->path_query(""); # reset the path
623 $urltop = $top_uri->as_string;
625 $v=$urltop.$v; # url relative to top of site
627 $v =~ s/\"/"/g; # since we quote with ""
628 substr($text, $v_offset, $v_len) = qq("$v");
632 }, "tagname, tokenpos, text");
640 my $itemtemplate=shift;
644 return unless $itemtemplate->query(name => "enclosure");
646 my $size=(srcfile_stat($file))[8];
648 eval q{use File::MimeInfo};
650 $mime = mimetype($file);
652 $itemtemplate->param(
659 sub genfeed ($$$$$@) {
668 my $url=URI->new(encode_utf8(urlto($page,"",1)));
670 my $itemtemplate=template_depends($feedtype."item.tmpl", $page, blind_cache => 1);
673 foreach my $p (@pages) {
674 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
675 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
676 my $fancy_enclosure_seen = 0;
678 $itemtemplate->param(
679 title => pagetitle(basename($p)),
682 cdate_822 => date_822($pagectime{$p}),
683 mdate_822 => date_822($pagemtime{$p}),
684 cdate_3339 => date_3339($pagectime{$p}),
685 mdate_3339 => date_3339($pagemtime{$p}),
688 if (exists $pagestate{$p}) {
689 if (exists $pagestate{$p}{meta}{guid}) {
690 eval q{use HTML::Entities};
691 $itemtemplate->param(guid => HTML::Entities::encode_numeric($pagestate{$p}{meta}{guid}));
694 if (exists $pagestate{$p}{meta}{updated}) {
695 $itemtemplate->param(mdate_822 => date_822($pagestate{$p}{meta}{updated}));
696 $itemtemplate->param(mdate_3339 => date_3339($pagestate{$p}{meta}{updated}));
699 if (exists $pagestate{$p}{meta}{enclosure}) {
700 my $absurl = $pagestate{$p}{meta}{enclosure};
701 my $file = $pagestate{$p}{meta}{enclosurefile};
702 genenclosure($itemtemplate, $absurl, $file);
703 $fancy_enclosure_seen = 1;
707 my $file=$pagesources{$p};
708 unless ($fancy_enclosure_seen || defined(pagetype($file))) {
709 genenclosure($itemtemplate, $u, $file);
710 $itemtemplate->param(simplepodcast => 1);
713 $itemtemplate->param(content => $pcontent);
715 run_hooks(pagetemplate => sub {
716 shift->(page => $p, destpage => $page,
717 template => $itemtemplate);
720 $content.=$itemtemplate->output;
721 $itemtemplate->clear_params;
723 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
726 my $template=template_depends($feedtype."page.tmpl", $page, blind_cache => 1);
728 wants_absolute_urls => 1,
730 wikiname => $config{wikiname},
733 feeddesc => $feeddesc,
735 feeddate => date_3339($lasttime),
736 feeddate_822 => date_822($lasttime),
739 run_hooks(pagetemplate => sub {
740 shift->(page => $page, destpage => $page,
741 template => $template);
744 return $template->output;
748 return unless @{$config{pingurl}} && %toping;
750 eval q{require RPC::XML::Client};
752 debug(gettext("RPC::XML::Client not found, not pinging"));
756 # daemonize here so slow pings don't slow down wiki updates
757 defined(my $pid = fork) or error("Can't fork: $!");
760 POSIX::setsid() or error("Can't start a new session: $!");
761 open STDIN, '/dev/null';
762 open STDOUT, '>/dev/null';
763 open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
765 # Don't need to keep a lock on the wiki as a daemon.
766 IkiWiki::unlockwiki();
768 foreach my $page (keys %toping) {
769 my $title=pagetitle(basename($page), 0);
770 my $url=urlto($page, "", 1);
771 foreach my $pingurl (@{$config{pingurl}}) {
772 debug("Pinging $pingurl for $page");
774 my $client = RPC::XML::Client->new($pingurl);
775 my $req = RPC::XML::request->new('weblogUpdates.ping',
777 my $res = $client->send_request($req);
779 error("Did not receive response to ping");
782 if (! exists $r->{flerror} || $r->{flerror}) {
783 error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
787 error "Ping failed: $@";
792 exit 0; # daemon done
800 if (exists $params{rootpage}) {
801 $rootpage=bestlink($params{page}, $params{rootpage});
802 if (!length $rootpage) {
803 $rootpage=$params{rootpage};
807 $rootpage=$params{page};