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});
184 if (! exists $params{show} && ! $archive) {
187 if (! exists $params{feedshow} && exists $params{show}) {
188 $params{feedshow}=$params{show};
191 if (exists $params{title}) {
192 $title = $params{title};
195 $title = $params{page} ne "index" ? pagetitle($params{page}) : $config{wikiname};
198 if (exists $params{description}) {
199 $desc = $params{description}
202 $desc = $config{wikiname};
204 my $actions=yesno($params{actions});
205 if (exists $params{template}) {
206 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
209 $params{template} = $archive ? "archivepage" : "inlinepage";
214 if (exists $params{pagenames}) {
215 foreach my $p (qw(sort pages)) {
216 if (exists $params{$p}) {
217 error sprintf(gettext("the %s and %s parameters cannot be used together"),
222 @list = split ' ', $params{pagenames};
224 if (yesno($params{reverse})) {
225 @list=reverse(@list);
228 foreach my $p (@list) {
229 add_depends($params{page}, $p, deptype($quick ? "presence" : "content"));
232 @list = grep { exists $pagesources{$_} } @list;
239 if ($params{feedshow} && $num < $params{feedshow} && $num > 0) {
240 $num=$params{feedshow};
242 if ($params{skip} && $num) {
246 @list = pagespec_match_list($params{page}, $params{pages},
247 deptype => deptype($quick ? "presence" : "content"),
248 filter => sub { $_[0] eq $params{page} },
249 sort => exists $params{sort} ? $params{sort} : "age title",
250 reverse => yesno($params{reverse}),
251 ($num ? (num => $num) : ()),
255 if (exists $params{skip}) {
256 @list=@list[$params{skip} .. $#list];
261 if (exists $params{feedshow} &&
262 $params{feedshow} && @list > $params{feedshow}) {
263 @feedlist=@list[0..$params{feedshow} - 1];
270 if ($params{show} && @list > $params{show}) {
271 @list=@list[0..$params{show} - 1];
274 if ($feeds && exists $params{feedpages}) {
275 @feedlist = pagespec_match_list(
276 $params{page}, "($params{pages}) and ($params{feedpages})",
277 deptype => deptype($quick ? "presence" : "content"),
282 my ($feedbase, $feednum);
284 # Ensure that multiple feeds on a page go to unique files.
286 # Feedfile can lead to conflicts if usedirs is not enabled,
287 # so avoid supporting it in that case.
288 delete $params{feedfile} if ! $config{usedirs};
289 # Tight limits on legal feedfiles, to avoid security issues
291 if (defined $params{feedfile}) {
292 if ($params{feedfile} =~ /\// ||
293 $params{feedfile} !~ /$config{wiki_file_regexp}/) {
294 error("illegal feedfile");
296 $params{feedfile}=possibly_foolish_untaint($params{feedfile});
298 $feedbase=targetpage($params{page}, "", $params{feedfile});
300 my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
301 if (exists $knownfeeds{$feedid}) {
302 $feednum=$knownfeeds{$feedid};
305 if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
307 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
311 $feednum=$knownfeeds{$feedid}="";
313 $page_numfeeds{$params{destpage}}{$feedbase}=1;
319 my ($rssurl, $atomurl, $rssdesc, $atomdesc);
322 $rssurl=abs2rel($feedbase."rss".$feednum, dirname(htmlpage($params{destpage})));
323 $rssdesc = sprintf(gettext("%s (RSS feed)"), $desc);
326 $atomurl=abs2rel($feedbase."atom".$feednum, dirname(htmlpage($params{destpage})));
327 $atomdesc = sprintf(gettext("%s (Atom feed)"), $desc);
333 my $postform = (exists $params{rootpage});
334 if (exists $params{postform}) {
335 $postform = yesno($params{postform});
338 if (length $config{cgiurl} && ! $params{preview} && $postform &&
339 IkiWiki->can("cgi_editpage")) {
340 # Add a blog post form, with feed buttons.
341 my $formtemplate=template_depends("blogpost.tmpl", $params{page}, blind_cache => 1);
342 $formtemplate->param(cgiurl => IkiWiki::cgiurl());
343 $formtemplate->param(rootpage => rootpage(%params));
346 $formtemplate->param(rssurl => $rssurl);
347 $formtemplate->param(rssdesc => $rssdesc);
350 $formtemplate->param(atomurl => $atomurl);
351 $formtemplate->param(atomdesc => $atomdesc);
354 if (exists $params{postformtext}) {
355 $formtemplate->param(postformtext =>
356 $params{postformtext});
359 $formtemplate->param(postformtext =>
360 gettext("Add a new post titled:"));
362 if (exists $params{id}) {
363 $formtemplate->param(postformid =>
366 $ret.=$formtemplate->output;
368 # The post form includes the feed buttons, so
369 # emptyfeeds cannot be hidden.
372 elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
374 my $linktemplate=template_depends("feedlink.tmpl", $params{page}, blind_cache => 1);
376 $linktemplate->param(rssurl => $rssurl);
377 $linktemplate->param(rssdesc => $rssdesc);
380 $linktemplate->param(atomurl => $atomurl);
381 $linktemplate->param(atomdesc => $atomdesc);
383 if (exists $params{id}) {
384 $linktemplate->param(id => $params{id});
386 $ret.=$linktemplate->output;
392 # cannot use wiki pages as templates; template not sanitized due to
395 $template=template_depends($params{template}.".tmpl", $params{page},
399 # gettext can clobber $@
401 error sprintf(gettext("failed to process template %s"), $params{template}.".tmpl").": $error";
404 my $needcontent=$raw || (!($archive && $quick) && $template->query(name => 'content'));
406 foreach my $page (@list) {
407 my $file = $pagesources{$page};
408 my $type = pagetype($file);
411 # Get the content before populating the
412 # template, since getting the content uses
413 # the same template if inlines are nested.
414 my $content=get_inline_content($page, $params{destpage});
415 $template->param(content => $content);
417 $template->param(pageurl => urlto($page, $params{destpage}));
418 $template->param(inlinepage => $page);
419 $template->param(title => pagetitle(basename($page)));
420 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}, 1));
421 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
422 $template->param(first => 1) if $page eq $list[0];
423 $template->param(last => 1) if $page eq $list[$#list];
424 $template->param(html5 => $config{html5});
427 my $file = $pagesources{$page};
428 my $type = pagetype($file);
429 if ($config{discussion}) {
430 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
431 (length $config{cgiurl} ||
432 exists $pagesources{$page."/".lc($config{discussionpage})})) {
433 $template->param(have_actions => 1);
434 $template->param(discussionlink =>
437 $config{discussionpage},
442 if (length $config{cgiurl} &&
444 IkiWiki->can("cgi_editpage")) {
445 $template->param(have_actions => 1);
446 $template->param(editurl => cgiurl(do => "edit", page => $page));
451 run_hooks(pagetemplate => sub {
452 shift->(page => $page, destpage => $params{destpage},
453 template => $template,);
456 $ret.=$template->output;
457 $template->clear_params;
462 linkify($page, $params{destpage},
463 preprocess($page, $params{destpage},
464 filter($page, $params{destpage},
465 readfile(srcfile($file)))));
469 readfile(srcfile($file));
475 if ($feeds && ($emptyfeeds || @feedlist)) {
477 my $rssp=$feedbase."rss".$feednum;
478 will_render($params{destpage}, $rssp);
479 if (! $params{preview}) {
480 writefile($rssp, $config{destdir},
482 $config{url}."/".$rssp, $title, $desc, $params{guid}, $params{page}, @feedlist));
483 $toping{$params{destpage}}=1 unless $config{rebuild};
484 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$rssdesc" href="$rssurl" />};
488 my $atomp=$feedbase."atom".$feednum;
489 will_render($params{destpage}, $atomp);
490 if (! $params{preview}) {
491 writefile($atomp, $config{destdir},
492 genfeed("atom", $config{url}."/".$atomp, $title, $desc, $params{guid}, $params{page}, @feedlist));
493 $toping{$params{destpage}}=1 unless $config{rebuild};
494 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$atomdesc" href="$atomurl" />};
499 clear_inline_content_cache();
501 return $ret if $raw || $nested;
503 return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
506 sub pagetemplate_inline (@) {
508 my $page=$params{page};
509 my $template=$params{template};
511 $template->param(feedlinks => $feedlinks{$page})
512 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
517 my $cached_destpage="";
519 sub get_inline_content ($$) {
523 if (exists $inline_content{$page} && $cached_destpage eq $destpage) {
524 return $inline_content{$page};
527 my $file=$pagesources{$page};
528 my $type=pagetype($file);
532 $ret=htmlize($page, $destpage, $type,
533 linkify($page, $destpage,
534 preprocess($page, $destpage,
535 filter($page, $destpage,
536 readfile(srcfile($file))))));
538 if (isinternal($page)) {
539 # make inlined text of internal pages searchable
540 run_hooks(indexhtml => sub {
541 shift->(page => $page, destpage => $destpage,
547 if ($cached_destpage ne $destpage) {
548 clear_inline_content_cache();
549 $cached_destpage=$destpage;
551 return $inline_content{$page}=$ret;
554 sub clear_inline_content_cache () {
563 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
564 POSIX::setlocale(&POSIX::LC_TIME, "C");
565 my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
566 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
570 sub absolute_urls ($$) {
571 # needed because rss sucks
577 my $urltop; # calculated if needed
581 eval q{use HTML::Parser; use HTML::Tagset};
583 my $p = HTML::Parser->new(api_version => 3);
584 $p->handler(default => sub { $ret.=join("", @_) }, "text");
585 $p->handler(start => sub {
586 my ($tagname, $pos, $text) = @_;
587 if (ref $HTML::Tagset::linkElements{$tagname}) {
589 # use attribute sets from right to left
590 # to avoid invalidating the offsets
591 # when replacing the values
592 my ($k_offset, $k_len, $v_offset, $v_len) =
594 my $attrname = lc(substr($text, $k_offset, $k_len));
595 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
596 next unless $v_offset; # 0 v_offset means no value
597 my $v = substr($text, $v_offset, $v_len);
598 $v =~ s/^([\'\"])(.*)\1$/$2/;
599 eval q{use HTML::Entities};
600 my $dv = decode_entities($v);
602 $v=$baseurl.$v; # anchor
604 elsif ($dv=~/^(?!\w+:)[^\/]/) {
605 $v=$url.$v; # relative url
608 if (! defined $urltop) {
609 # what is the non path part of the url?
610 my $top_uri = URI->new($url);
611 $top_uri->path_query(""); # reset the path
612 $urltop = $top_uri->as_string;
614 $v=$urltop.$v; # url relative to top of site
616 $v =~ s/\"/"/g; # since we quote with ""
617 substr($text, $v_offset, $v_len) = qq("$v");
621 }, "tagname, tokenpos, text");
629 my $itemtemplate=shift;
633 return unless $itemtemplate->query(name => "enclosure");
635 my $size=(srcfile_stat($file))[8];
637 eval q{use File::MimeInfo};
639 $mime = mimetype($file);
641 $itemtemplate->param(
648 sub genfeed ($$$$$@) {
657 my $url=URI->new(encode_utf8(urlto($page,"",1)));
659 my $itemtemplate=template_depends($feedtype."item.tmpl", $page, blind_cache => 1);
662 foreach my $p (@pages) {
663 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
664 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
665 my $fancy_enclosure_seen = 0;
667 $itemtemplate->param(
668 title => pagetitle(basename($p)),
671 cdate_822 => date_822($pagectime{$p}),
672 mdate_822 => date_822($pagemtime{$p}),
673 cdate_3339 => date_3339($pagectime{$p}),
674 mdate_3339 => date_3339($pagemtime{$p}),
677 if (exists $pagestate{$p}) {
678 if (exists $pagestate{$p}{meta}{guid}) {
679 eval q{use HTML::Entities};
680 $itemtemplate->param(guid => HTML::Entities::encode_numeric($pagestate{$p}{meta}{guid}));
683 if (exists $pagestate{$p}{meta}{updated}) {
684 $itemtemplate->param(mdate_822 => date_822($pagestate{$p}{meta}{updated}));
685 $itemtemplate->param(mdate_3339 => date_3339($pagestate{$p}{meta}{updated}));
688 if (exists $pagestate{$p}{meta}{enclosure}) {
689 my $absurl = $pagestate{$p}{meta}{enclosure};
690 my $file = $pagestate{$p}{meta}{enclosurefile};
691 genenclosure($itemtemplate, $absurl, $file);
692 $fancy_enclosure_seen = 1;
696 my $file=$pagesources{$p};
697 unless ($fancy_enclosure_seen || defined(pagetype($file))) {
698 genenclosure($itemtemplate, $u, $file);
699 $itemtemplate->param(simplepodcast => 1);
702 $itemtemplate->param(content => $pcontent);
704 run_hooks(pagetemplate => sub {
705 shift->(page => $p, destpage => $page,
706 template => $itemtemplate);
709 $content.=$itemtemplate->output;
710 $itemtemplate->clear_params;
712 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
715 my $template=template_depends($feedtype."page.tmpl", $page, blind_cache => 1);
718 wikiname => $config{wikiname},
721 feeddesc => $feeddesc,
723 feeddate => date_3339($lasttime),
724 feeddate_822 => date_822($lasttime),
727 run_hooks(pagetemplate => sub {
728 shift->(page => $page, destpage => $page,
729 template => $template);
732 return $template->output;
736 return unless @{$config{pingurl}} && %toping;
738 eval q{require RPC::XML::Client};
740 debug(gettext("RPC::XML::Client not found, not pinging"));
744 # daemonize here so slow pings don't slow down wiki updates
745 defined(my $pid = fork) or error("Can't fork: $!");
748 POSIX::setsid() or error("Can't start a new session: $!");
749 open STDIN, '/dev/null';
750 open STDOUT, '>/dev/null';
751 open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
753 # Don't need to keep a lock on the wiki as a daemon.
754 IkiWiki::unlockwiki();
756 foreach my $page (keys %toping) {
757 my $title=pagetitle(basename($page), 0);
758 my $url=urlto($page, "", 1);
759 foreach my $pingurl (@{$config{pingurl}}) {
760 debug("Pinging $pingurl for $page");
762 my $client = RPC::XML::Client->new($pingurl);
763 my $req = RPC::XML::request->new('weblogUpdates.ping',
765 my $res = $client->send_request($req);
767 error("Did not receive response to ping");
770 if (! exists $r->{flerror} || $r->{flerror}) {
771 error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
775 error "Ping failed: $@";
780 exit 0; # daemon done
788 if (exists $params{rootpage}) {
789 $rootpage=bestlink($params{page}, $params{rootpage});
790 if (!length $rootpage) {
791 $rootpage=$params{rootpage};
795 $rootpage=$params{page};