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 (! length $page) {
125 error(gettext("please enter a page title"));
127 # if the page already exists, munge it to be unique
128 my $from=$q->param('from');
130 while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
131 $add=1 unless length $add;
134 $q->param('page', "/$from/$page$add");
135 # now go create the page
136 $q->param('do', 'create');
137 # make sure the editpage plugin is loaded
138 if (IkiWiki->can("cgi_editpage")) {
139 IkiWiki::cgi_editpage($q, $session);
142 error(gettext("page editing not allowed"));
148 # Back to ikiwiki namespace for the rest, this code is very much
149 # internal to ikiwiki even though it's separated into a plugin.
155 sub preprocess_inline (@) {
158 if (! exists $params{pages} && ! exists $params{pagenames}) {
159 error gettext("missing pages parameter");
162 if (! defined wantarray) {
163 # Running in scan mode: only do the essentials
165 if (yesno($params{trail}) && IkiWiki::Plugin::trail->can("preprocess_trailitems")) {
166 # default to sorting by age with fallback to title,
167 # the same as inline itself, but let the params
169 IkiWiki::Plugin::trail::preprocess_trailitems(sort => 'age title', %params);
175 if (yesno($params{trail}) && IkiWiki::Plugin::trail->can("preprocess_trailitems")) {
176 scalar IkiWiki::Plugin::trail::preprocess_trailitems(sort => 'age title', %params);
179 my $raw=yesno($params{raw});
180 my $archive=yesno($params{archive});
181 my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
182 my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
183 my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
184 my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick && ! $raw;
185 my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
186 my $feedonly=yesno($params{feedonly});
188 # Backwards compatibility
189 if (defined $params{show} && $params{show} =~ m/^-?\d+$/) {
190 $params{limit} = $params{show};
191 delete $params{show};
193 if (defined $params{feedshow} && $params{feedshow} =~ m/^\d+$/) {
194 $params{feedlimit} = $params{feedshow};
195 delete $params{feedshow};
198 if (! exists $params{limit} && ! $archive) {
201 if (! exists $params{feedlimit} && exists $params{limit}) {
202 $params{feedlimit}=$params{limit};
205 if (exists $params{title}) {
206 $title = $params{title};
209 $title = $params{page} ne "index" ? pagetitle($params{page}) : $config{wikiname};
212 if (exists $params{description}) {
213 $desc = $params{description}
216 $desc = $config{wikiname};
218 my $actions=yesno($params{actions});
219 if (exists $params{template}) {
220 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
223 $params{template} = $archive ? "archivepage" : "inlinepage";
228 if (exists $params{pagenames}) {
229 foreach my $p (qw(sort pages)) {
230 if (exists $params{$p}) {
231 error sprintf(gettext("the %s and %s parameters cannot be used together"),
236 @list = split ' ', $params{pagenames};
238 if (yesno($params{reverse})) {
239 @list=reverse(@list);
242 foreach my $p (@list) {
243 add_depends($params{page}, $p, deptype($quick ? "presence" : "content"));
246 @list = grep { exists $pagesources{$_} } @list;
250 if ($params{limit}) {
253 if ($params{feedlimit} && $num < $params{feedlimit} && $num > 0) {
254 $num=$params{feedlimit};
256 if ($params{skip} && $num) {
260 @list = pagespec_match_list($params{page}, $params{pages},
261 deptype => deptype($quick ? "presence" : "content"),
262 filter => sub { $_[0] eq $params{page} },
263 sort => exists $params{sort} ? $params{sort} : "age title",
264 reverse => yesno($params{reverse}),
265 ($num ? (num => $num) : ()),
269 if (exists $params{skip}) {
270 @list=@list[$params{skip} .. $#list];
275 if (exists $params{feedlimit} &&
276 $params{feedlimit} && @list > $params{feedlimit}) {
277 @feedlist=@list[0..$params{feedlimit} - 1];
284 if ($params{limit} && @list > $params{limit}) {
285 @list=@list[0..$params{limit} - 1];
288 if ($feeds && exists $params{feedpages}) {
289 @feedlist = pagespec_match_list(
290 $params{page}, "($params{pages}) and ($params{feedpages})",
291 deptype => deptype($quick ? "presence" : "content"),
296 my ($feedbase, $feednum);
298 # Ensure that multiple feeds on a page go to unique files.
300 # Feedfile can lead to conflicts if usedirs is not enabled,
301 # so avoid supporting it in that case.
302 delete $params{feedfile} if ! $config{usedirs};
303 # Tight limits on legal feedfiles, to avoid security issues
305 if (defined $params{feedfile}) {
306 if ($params{feedfile} =~ /\// ||
307 $params{feedfile} !~ /$config{wiki_file_regexp}/) {
308 error("illegal feedfile");
310 $params{feedfile}=possibly_foolish_untaint($params{feedfile});
312 $feedbase=targetpage($params{page}, "", $params{feedfile});
314 my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
315 if (exists $knownfeeds{$feedid}) {
316 $feednum=$knownfeeds{$feedid};
319 if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
321 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
325 $feednum=$knownfeeds{$feedid}="";
327 $page_numfeeds{$params{destpage}}{$feedbase}=1;
333 my ($rssurl, $atomurl, $rssdesc, $atomdesc);
336 $rssurl=abs2rel($feedbase."rss".$feednum, dirname(htmlpage($params{destpage})));
337 $rssdesc = sprintf(gettext("%s (RSS feed)"), $desc);
340 $atomurl=abs2rel($feedbase."atom".$feednum, dirname(htmlpage($params{destpage})));
341 $atomdesc = sprintf(gettext("%s (Atom feed)"), $desc);
347 my $postform = (exists $params{rootpage});
348 if (exists $params{postform}) {
349 $postform = yesno($params{postform});
352 if (length $config{cgiurl} && ! $params{preview} && $postform &&
353 IkiWiki->can("cgi_editpage")) {
354 # Add a blog post form, with feed buttons.
355 my $formtemplate=template_depends("blogpost.tmpl", $params{page}, blind_cache => 1);
356 $formtemplate->param(cgiurl => IkiWiki::cgiurl());
357 $formtemplate->param(rootpage => rootpage(%params));
360 $formtemplate->param(rssurl => $rssurl);
361 $formtemplate->param(rssdesc => $rssdesc);
364 $formtemplate->param(atomurl => $atomurl);
365 $formtemplate->param(atomdesc => $atomdesc);
368 if (exists $params{postformtext}) {
369 $formtemplate->param(postformtext =>
370 $params{postformtext});
373 $formtemplate->param(postformtext =>
374 gettext("Add a new post titled:"));
376 if (exists $params{id}) {
377 $formtemplate->param(postformid =>
380 $ret.=$formtemplate->output;
382 # The post form includes the feed buttons, so
383 # emptyfeeds cannot be hidden.
386 elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
388 my $linktemplate=template_depends("feedlink.tmpl", $params{page}, blind_cache => 1);
390 $linktemplate->param(rssurl => $rssurl);
391 $linktemplate->param(rssdesc => $rssdesc);
394 $linktemplate->param(atomurl => $atomurl);
395 $linktemplate->param(atomdesc => $atomdesc);
397 if (exists $params{id}) {
398 $linktemplate->param(id => $params{id});
400 $ret.=$linktemplate->output;
406 # cannot use wiki pages as templates; template not sanitized due to
409 $template=template_depends($params{template}.".tmpl", $params{page},
413 # gettext can clobber $@
415 error sprintf(gettext("failed to process template %s"), $params{template}.".tmpl").": $error";
418 my $needcontent=$raw || (!($archive && $quick) && $template->query(name => 'content'));
420 foreach my $page (@list) {
421 my $file = $pagesources{$page};
422 my $type = pagetype($file);
425 # Get the content before populating the
426 # template, since getting the content uses
427 # the same template if inlines are nested.
428 my $content=get_inline_content($page, $params{destpage});
429 $template->param(content => $content);
431 $template->param(pageurl => urlto($page, $params{destpage}));
432 $template->param(inlinepage => $page);
433 $template->param(title => pagetitle(basename($page)));
434 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}, 1));
435 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
436 $template->param(first => 1) if $page eq $list[0];
437 $template->param(last => 1) if $page eq $list[$#list];
438 $template->param(html5 => $config{html5});
441 my $file = $pagesources{$page};
442 my $type = pagetype($file);
443 if ($config{discussion}) {
444 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
445 (length $config{cgiurl} ||
446 exists $pagesources{$page."/".lc($config{discussionpage})})) {
447 $template->param(have_actions => 1);
448 $template->param(discussionlink =>
451 $config{discussionpage},
456 if (length $config{cgiurl} &&
458 IkiWiki->can("cgi_editpage")) {
459 $template->param(have_actions => 1);
460 $template->param(editurl => cgiurl(do => "edit", page => $page));
465 run_hooks(pagetemplate => sub {
466 shift->(page => $page, destpage => $params{destpage},
467 template => $template,);
470 $ret.=$template->output;
471 $template->clear_params;
476 linkify($page, $params{destpage},
477 preprocess($page, $params{destpage},
478 filter($page, $params{destpage},
479 readfile(srcfile($file)))));
483 readfile(srcfile($file));
489 if ($feeds && ($emptyfeeds || @feedlist)) {
491 my $rssp=$feedbase."rss".$feednum;
492 will_render($params{destpage}, $rssp);
493 if (! $params{preview}) {
494 writefile($rssp, $config{destdir},
496 $config{url}."/".$rssp, $title, $desc, $params{guid}, $params{page}, @feedlist));
497 $toping{$params{destpage}}=1 unless $config{rebuild};
498 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$rssdesc" href="$rssurl" />};
502 my $atomp=$feedbase."atom".$feednum;
503 will_render($params{destpage}, $atomp);
504 if (! $params{preview}) {
505 writefile($atomp, $config{destdir},
506 genfeed("atom", $config{url}."/".$atomp, $title, $desc, $params{guid}, $params{page}, @feedlist));
507 $toping{$params{destpage}}=1 unless $config{rebuild};
508 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$atomdesc" href="$atomurl" />};
513 clear_inline_content_cache();
515 return $ret if $raw || $nested;
517 return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
520 sub pagetemplate_inline (@) {
522 my $page=$params{page};
523 my $template=$params{template};
525 $template->param(feedlinks => $feedlinks{$page})
526 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
531 my $cached_destpage="";
533 sub get_inline_content ($$) {
537 if (exists $inline_content{$page} && $cached_destpage eq $destpage) {
538 return $inline_content{$page};
541 my $file=$pagesources{$page};
542 my $type=pagetype($file);
546 $ret=htmlize($page, $destpage, $type,
547 linkify($page, $destpage,
548 preprocess($page, $destpage,
549 filter($page, $destpage,
550 readfile(srcfile($file))))));
552 if (isinternal($page)) {
553 # make inlined text of internal pages searchable
554 run_hooks(indexhtml => sub {
555 shift->(page => $page, destpage => $destpage,
561 if ($cached_destpage ne $destpage) {
562 clear_inline_content_cache();
563 $cached_destpage=$destpage;
565 return $inline_content{$page}=$ret;
568 sub clear_inline_content_cache () {
577 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
578 POSIX::setlocale(&POSIX::LC_TIME, "C");
579 my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
580 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
584 sub absolute_urls ($$) {
585 # needed because rss sucks
591 my $urltop; # calculated if needed
595 eval q{use HTML::Parser; use HTML::Tagset};
597 my $p = HTML::Parser->new(api_version => 3);
598 $p->handler(default => sub { $ret.=join("", @_) }, "text");
599 $p->handler(start => sub {
600 my ($tagname, $pos, $text) = @_;
601 if (ref $HTML::Tagset::linkElements{$tagname}) {
603 # use attribute sets from right to left
604 # to avoid invalidating the offsets
605 # when replacing the values
606 my ($k_offset, $k_len, $v_offset, $v_len) =
608 my $attrname = lc(substr($text, $k_offset, $k_len));
609 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
610 next unless $v_offset; # 0 v_offset means no value
611 my $v = substr($text, $v_offset, $v_len);
612 $v =~ s/^([\'\"])(.*)\1$/$2/;
613 eval q{use HTML::Entities};
614 my $dv = decode_entities($v);
616 $v=$baseurl.$v; # anchor
618 elsif ($dv=~/^(?!\w+:)[^\/]/) {
619 $v=URI->new_abs($v, $url)->canonical; # relative url
622 if (! defined $urltop) {
623 # what is the non path part of the url?
624 my $top_uri = URI->new($url);
625 $top_uri->path_query(""); # reset the path
626 $urltop = $top_uri->as_string;
628 $v=$urltop.$v; # url relative to top of site
630 $v =~ s/\"/"/g; # since we quote with ""
631 substr($text, $v_offset, $v_len) = qq("$v");
635 }, "tagname, tokenpos, text");
643 my $itemtemplate=shift;
647 return unless $itemtemplate->query(name => "enclosure");
649 my $size=(srcfile_stat($file))[8];
651 eval q{use File::MimeInfo};
653 $mime = mimetype($file);
655 $itemtemplate->param(
662 sub genfeed ($$$$$@) {
671 my $url=URI->new(encode_utf8(urlto($page,"",1)));
673 my $itemtemplate=template_depends($feedtype."item.tmpl", $page, blind_cache => 1);
676 foreach my $p (@pages) {
677 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
678 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
679 my $fancy_enclosure_seen = 0;
681 $itemtemplate->param(
682 title => pagetitle(basename($p)),
685 cdate_822 => date_822($pagectime{$p}),
686 mdate_822 => date_822($pagemtime{$p}),
687 cdate_3339 => date_3339($pagectime{$p}),
688 mdate_3339 => date_3339($pagemtime{$p}),
691 if (exists $pagestate{$p}) {
692 if (exists $pagestate{$p}{meta}{guid}) {
693 eval q{use HTML::Entities};
694 $itemtemplate->param(guid => HTML::Entities::encode_numeric($pagestate{$p}{meta}{guid}));
697 if (exists $pagestate{$p}{meta}{updated}) {
698 $itemtemplate->param(mdate_822 => date_822($pagestate{$p}{meta}{updated}));
699 $itemtemplate->param(mdate_3339 => date_3339($pagestate{$p}{meta}{updated}));
702 if (exists $pagestate{$p}{meta}{enclosure}) {
703 my $absurl = $pagestate{$p}{meta}{enclosure};
704 my $file = $pagestate{$p}{meta}{enclosurefile};
705 genenclosure($itemtemplate, $absurl, $file);
706 $fancy_enclosure_seen = 1;
710 my $file=$pagesources{$p};
711 unless ($fancy_enclosure_seen || defined(pagetype($file))) {
712 genenclosure($itemtemplate, $u, $file);
713 $itemtemplate->param(simplepodcast => 1);
716 $itemtemplate->param(content => $pcontent);
718 run_hooks(pagetemplate => sub {
719 shift->(page => $p, destpage => $page,
720 template => $itemtemplate);
723 $content.=$itemtemplate->output;
724 $itemtemplate->clear_params;
726 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
729 my $template=template_depends($feedtype."page.tmpl", $page, blind_cache => 1);
731 wants_absolute_urls => 1,
733 wikiname => $config{wikiname},
736 feeddesc => $feeddesc,
738 feeddate => date_3339($lasttime),
739 feeddate_822 => date_822($lasttime),
742 run_hooks(pagetemplate => sub {
743 shift->(page => $page, destpage => $page,
744 template => $template);
747 return $template->output;
751 return unless @{$config{pingurl}} && %toping;
753 eval q{require RPC::XML::Client};
755 debug(gettext("RPC::XML::Client not found, not pinging"));
759 # daemonize here so slow pings don't slow down wiki updates
760 defined(my $pid = fork) or error("Can't fork: $!");
763 POSIX::setsid() or error("Can't start a new session: $!");
764 open STDIN, '/dev/null';
765 open STDOUT, '>/dev/null';
766 open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
768 # Don't need to keep a lock on the wiki as a daemon.
769 IkiWiki::unlockwiki();
771 foreach my $page (keys %toping) {
772 my $title=pagetitle(basename($page), 0);
773 my $url=urlto($page, "", 1);
774 foreach my $pingurl (@{$config{pingurl}}) {
775 debug("Pinging $pingurl for $page");
777 my $client = RPC::XML::Client->new($pingurl);
778 my $req = RPC::XML::request->new('weblogUpdates.ping',
780 my $res = $client->send_request($req);
782 error("Did not receive response to ping");
785 if (! exists $r->{flerror} || $r->{flerror}) {
786 error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
790 error "Ping failed: $@";
795 exit 0; # daemon done
803 if (exists $params{rootpage}) {
804 $rootpage=bestlink($params{page}, $params{rootpage});
805 if (!length $rootpage) {
806 $rootpage=$params{rootpage};
810 $rootpage=$params{page};