Added my site, even though it's in an early state
[ikiwiki.git] / IkiWiki / Plugin / inline.pm
blob28507720403f4da7940b2a55d2a72ad357d58664
1 #!/usr/bin/perl
2 # Page inlining and blogging.
3 package IkiWiki::Plugin::inline;
5 use warnings;
6 use strict;
7 use Encode;
8 use IkiWiki 3.00;
9 use URI;
11 my %knownfeeds;
12 my %page_numfeeds;
13 my @inline;
14 my $nested=0;
16 sub import {
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);
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 => "change", id => "inline", call => \&IkiWiki::pingurl);
32 sub getopt () {
33 eval q{use Getopt::Long};
34 error($@) if $@;
35 Getopt::Long::Configure('pass_through');
36 GetOptions(
37 "rss!" => \$config{rss},
38 "atom!" => \$config{atom},
39 "allowrss!" => \$config{allowrss},
40 "allowatom!" => \$config{allowatom},
41 "pingurl=s" => sub {
42 push @{$config{pingurl}}, $_[1];
43 },
47 sub getsetup () {
48 return
49 plugin => {
50 safe => 1,
51 rebuild => undef,
52 section => "core",
54 rss => {
55 type => "boolean",
56 example => 0,
57 description => "enable rss feeds by default?",
58 safe => 1,
59 rebuild => 1,
61 atom => {
62 type => "boolean",
63 example => 0,
64 description => "enable atom feeds by default?",
65 safe => 1,
66 rebuild => 1,
68 allowrss => {
69 type => "boolean",
70 example => 0,
71 description => "allow rss feeds to be used?",
72 safe => 1,
73 rebuild => 1,
75 allowatom => {
76 type => "boolean",
77 example => 0,
78 description => "allow atom feeds to be used?",
79 safe => 1,
80 rebuild => 1,
82 pingurl => {
83 type => "string",
84 example => "http://rpc.technorati.com/rpc/ping",
85 description => "urls to ping (using XML-RPC) on feed update",
86 safe => 1,
87 rebuild => 0,
91 sub checkconfig () {
92 if (($config{rss} || $config{atom}) && ! length $config{url}) {
93 error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
95 if ($config{rss}) {
96 push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
98 if ($config{atom}) {
99 push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
101 if (! exists $config{pingurl}) {
102 $config{pingurl}=[];
106 sub format (@) {
107 my %params=@_;
109 # Fill in the inline content generated earlier. This is actually an
110 # optimisation.
111 $params{content}=~s{<div class="inline" id="([^"]+)"></div>}{
112 delete @inline[$1,]
113 }eg;
114 return $params{content};
117 sub sessioncgi ($$) {
118 my $q=shift;
119 my $session=shift;
121 if ($q->param('do') eq 'blog') {
122 my $page=titlepage(decode_utf8($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');
126 my $add="";
127 while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
128 $add=1 unless length $add;
129 $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);
138 else {
139 error(gettext("page editing not allowed"));
141 exit;
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.
147 package IkiWiki;
149 my %toping;
150 my %feedlinks;
152 sub preprocess_inline (@) {
153 my %params=@_;
155 if (! exists $params{pages} && ! exists $params{pagenames}) {
156 error gettext("missing pages parameter");
158 my $raw=yesno($params{raw});
159 my $archive=yesno($params{archive});
160 my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
161 my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
162 my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
163 my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick && ! $raw;
164 my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
165 my $feedonly=yesno($params{feedonly});
166 if (! exists $params{show} && ! $archive) {
167 $params{show}=10;
169 if (! exists $params{feedshow} && exists $params{show}) {
170 $params{feedshow}=$params{show};
172 my $desc;
173 if (exists $params{description}) {
174 $desc = $params{description}
176 else {
177 $desc = $config{wikiname};
179 my $actions=yesno($params{actions});
180 if (exists $params{template}) {
181 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
183 else {
184 $params{template} = $archive ? "archivepage" : "inlinepage";
187 my @list;
189 if (exists $params{pagenames}) {
190 foreach my $p (qw(sort pages)) {
191 if (exists $params{$p}) {
192 error sprintf(gettext("the %s and %s parameters cannot be used together"),
193 "pagenames", $p);
197 @list = map { bestlink($params{page}, $_) }
198 split ' ', $params{pagenames};
200 if (yesno($params{reverse})) {
201 @list=reverse(@list);
204 foreach my $p (@list) {
205 add_depends($params{page}, $p, deptype($quick ? "presence" : "content"));
208 else {
209 my $num=0;
210 if ($params{show}) {
211 $num=$params{show};
213 if ($params{feedshow} && $num < $params{feedshow} && $num > 0) {
214 $num=$params{feedshow};
216 if ($params{skip} && $num) {
217 $num+=$params{skip};
220 @list = pagespec_match_list($params{page}, $params{pages},
221 deptype => deptype($quick ? "presence" : "content"),
222 filter => sub { $_[0] eq $params{page} },
223 sort => exists $params{sort} ? $params{sort} : "age",
224 reverse => yesno($params{reverse}),
225 ($num ? (num => $num) : ()),
229 if (exists $params{skip}) {
230 @list=@list[$params{skip} .. $#list];
233 my @feedlist;
234 if ($feeds) {
235 if (exists $params{feedshow} &&
236 $params{feedshow} && @list > $params{feedshow}) {
237 @feedlist=@list[0..$params{feedshow} - 1];
239 else {
240 @feedlist=@list;
244 if ($params{show} && @list > $params{show}) {
245 @list=@list[0..$params{show} - 1];
248 if ($feeds && exists $params{feedpages}) {
249 @feedlist = pagespec_match_list(
250 $params{page}, "($params{pages}) and ($params{feedpages})",
251 deptype => deptype($quick ? "presence" : "content"),
252 list => \@feedlist,
256 my ($feedbase, $feednum);
257 if ($feeds) {
258 # Ensure that multiple feeds on a page go to unique files.
260 # Feedfile can lead to conflicts if usedirs is not enabled,
261 # so avoid supporting it in that case.
262 delete $params{feedfile} if ! $config{usedirs};
263 # Tight limits on legal feedfiles, to avoid security issues
264 # and conflicts.
265 if (defined $params{feedfile}) {
266 if ($params{feedfile} =~ /\// ||
267 $params{feedfile} !~ /$config{wiki_file_regexp}/) {
268 error("illegal feedfile");
270 $params{feedfile}=possibly_foolish_untaint($params{feedfile});
272 $feedbase=targetpage($params{page}, "", $params{feedfile});
274 my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
275 if (exists $knownfeeds{$feedid}) {
276 $feednum=$knownfeeds{$feedid};
278 else {
279 if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
280 if ($feeds) {
281 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
284 else {
285 $feednum=$knownfeeds{$feedid}="";
286 if ($feeds) {
287 $page_numfeeds{$params{destpage}}{$feedbase}=1;
293 my ($rssurl, $atomurl, $rssdesc, $atomdesc);
294 if ($feeds) {
295 if ($rss) {
296 $rssurl=abs2rel($feedbase."rss".$feednum, dirname(htmlpage($params{destpage})));
297 $rssdesc = sprintf(gettext("%s (RSS feed)"), $desc);
299 if ($atom) {
300 $atomurl=abs2rel($feedbase."atom".$feednum, dirname(htmlpage($params{destpage})));
301 $atomdesc = sprintf(gettext("%s (Atom feed)"), $desc);
305 my $ret="";
307 if (length $config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
308 (exists $params{postform} && yesno($params{postform}))) &&
309 IkiWiki->can("cgi_editpage")) {
310 # Add a blog post form, with feed buttons.
311 my $formtemplate=template_depends("blogpost.tmpl", $params{page}, blind_cache => 1);
312 $formtemplate->param(cgiurl => IkiWiki::cgiurl());
313 $formtemplate->param(rootpage => rootpage(%params));
314 if ($feeds) {
315 if ($rss) {
316 $formtemplate->param(rssurl => $rssurl);
317 $formtemplate->param(rssdesc => $rssdesc);
319 if ($atom) {
320 $formtemplate->param(atomurl => $atomurl);
321 $formtemplate->param(atomdesc => $atomdesc);
324 if (exists $params{postformtext}) {
325 $formtemplate->param(postformtext =>
326 $params{postformtext});
328 else {
329 $formtemplate->param(postformtext =>
330 gettext("Add a new post titled:"));
332 $ret.=$formtemplate->output;
334 # The post form includes the feed buttons, so
335 # emptyfeeds cannot be hidden.
336 $emptyfeeds=1;
338 elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
339 # Add feed buttons.
340 my $linktemplate=template_depends("feedlink.tmpl", $params{page}, blind_cache => 1);
341 if ($rss) {
342 $linktemplate->param(rssurl => $rssurl);
343 $linktemplate->param(rssdesc => $rssdesc);
345 if ($atom) {
346 $linktemplate->param(atomurl => $atomurl);
347 $linktemplate->param(atomdesc => $atomdesc);
349 $ret.=$linktemplate->output;
352 if (! $feedonly) {
353 my $template;
354 if (! $raw) {
355 # cannot use wiki pages as templates; template not sanitized due to
356 # format hook hack
357 eval {
358 $template=template_depends($params{template}.".tmpl", $params{page},
359 blind_cache => 1);
361 if ($@) {
362 error sprintf(gettext("failed to process template %s"), $params{template}.".tmpl").": $@";
365 my $needcontent=$raw || (!($archive && $quick) && $template->query(name => 'content'));
367 foreach my $page (@list) {
368 my $file = $pagesources{$page};
369 my $type = pagetype($file);
370 if (! $raw) {
371 if ($needcontent) {
372 # Get the content before populating the
373 # template, since getting the content uses
374 # the same template if inlines are nested.
375 my $content=get_inline_content($page, $params{destpage});
376 $template->param(content => $content);
378 $template->param(pageurl => urlto($page, $params{destpage}));
379 $template->param(inlinepage => $page);
380 $template->param(title => pagetitle(basename($page)));
381 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}, 1));
382 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
383 $template->param(first => 1) if $page eq $list[0];
384 $template->param(last => 1) if $page eq $list[$#list];
385 $template->param(html5 => $config{html5});
387 if ($actions) {
388 my $file = $pagesources{$page};
389 my $type = pagetype($file);
390 if ($config{discussion}) {
391 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
392 (length $config{cgiurl} ||
393 exists $pagesources{$page."/".lc($config{discussionpage})})) {
394 $template->param(have_actions => 1);
395 $template->param(discussionlink =>
396 htmllink($page,
397 $params{destpage},
398 $config{discussionpage},
399 noimageinline => 1,
400 forcesubpage => 1));
403 if (length $config{cgiurl} &&
404 defined $type &&
405 IkiWiki->can("cgi_editpage")) {
406 $template->param(have_actions => 1);
407 $template->param(editurl => cgiurl(do => "edit", page => $page));
412 run_hooks(pagetemplate => sub {
413 shift->(page => $page, destpage => $params{destpage},
414 template => $template,);
417 $ret.=$template->output;
418 $template->clear_params;
420 else {
421 if (defined $type) {
422 $ret.="\n".
423 linkify($page, $params{destpage},
424 preprocess($page, $params{destpage},
425 filter($page, $params{destpage},
426 readfile(srcfile($file)))));
428 else {
429 $ret.="\n".
430 readfile(srcfile($file));
436 if ($feeds && ($emptyfeeds || @feedlist)) {
437 if ($rss) {
438 my $rssp=$feedbase."rss".$feednum;
439 will_render($params{destpage}, $rssp);
440 if (! $params{preview}) {
441 writefile($rssp, $config{destdir},
442 genfeed("rss",
443 $config{url}."/".$rssp, $desc, $params{guid}, $params{destpage}, @feedlist));
444 $toping{$params{destpage}}=1 unless $config{rebuild};
445 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$rssdesc" href="$rssurl" />};
448 if ($atom) {
449 my $atomp=$feedbase."atom".$feednum;
450 will_render($params{destpage}, $atomp);
451 if (! $params{preview}) {
452 writefile($atomp, $config{destdir},
453 genfeed("atom", $config{url}."/".$atomp, $desc, $params{guid}, $params{destpage}, @feedlist));
454 $toping{$params{destpage}}=1 unless $config{rebuild};
455 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$atomdesc" href="$atomurl" />};
460 clear_inline_content_cache();
462 return $ret if $raw || $nested;
463 push @inline, $ret;
464 return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
467 sub pagetemplate_inline (@) {
468 my %params=@_;
469 my $page=$params{page};
470 my $template=$params{template};
472 $template->param(feedlinks => $feedlinks{$page})
473 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
477 my %inline_content;
478 my $cached_destpage="";
480 sub get_inline_content ($$) {
481 my $page=shift;
482 my $destpage=shift;
484 if (exists $inline_content{$page} && $cached_destpage eq $destpage) {
485 return $inline_content{$page};
488 my $file=$pagesources{$page};
489 my $type=pagetype($file);
490 my $ret="";
491 if (defined $type) {
492 $nested++;
493 $ret=htmlize($page, $destpage, $type,
494 linkify($page, $destpage,
495 preprocess($page, $destpage,
496 filter($page, $destpage,
497 readfile(srcfile($file))))));
498 $nested--;
499 if (isinternal($page)) {
500 # make inlined text of internal pages searchable
501 run_hooks(indexhtml => sub {
502 shift->(page => $page, destpage => $page,
503 content => $ret);
508 if ($cached_destpage ne $destpage) {
509 clear_inline_content_cache();
510 $cached_destpage=$destpage;
512 return $inline_content{$page}=$ret;
515 sub clear_inline_content_cache () {
516 %inline_content=();
521 sub date_822 ($) {
522 my $time=shift;
524 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
525 POSIX::setlocale(&POSIX::LC_TIME, "C");
526 my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
527 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
528 return $ret;
531 sub absolute_urls ($$) {
532 # needed because rss sucks
533 my $html=shift;
534 my $baseurl=shift;
536 my $url=$baseurl;
537 $url=~s/[^\/]+$//;
538 my $urltop; # calculated if needed
540 my $ret="";
542 eval q{use HTML::Parser; use HTML::Tagset};
543 die $@ if $@;
544 my $p = HTML::Parser->new(api_version => 3);
545 $p->handler(default => sub { $ret.=join("", @_) }, "text");
546 $p->handler(start => sub {
547 my ($tagname, $pos, $text) = @_;
548 if (ref $HTML::Tagset::linkElements{$tagname}) {
549 while (4 <= @$pos) {
550 # use attribute sets from right to left
551 # to avoid invalidating the offsets
552 # when replacing the values
553 my ($k_offset, $k_len, $v_offset, $v_len) =
554 splice(@$pos, -4);
555 my $attrname = lc(substr($text, $k_offset, $k_len));
556 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
557 next unless $v_offset; # 0 v_offset means no value
558 my $v = substr($text, $v_offset, $v_len);
559 $v =~ s/^([\'\"])(.*)\1$/$2/;
560 if ($v=~/^#/) {
561 $v=$baseurl.$v; # anchor
563 elsif ($v=~/^(?!\w+:)[^\/]/) {
564 $v=$url.$v; # relative url
566 elsif ($v=~/^\//) {
567 if (! defined $urltop) {
568 # what is the non path part of the url?
569 my $top_uri = URI->new($url);
570 $top_uri->path_query(""); # reset the path
571 $urltop = $top_uri->as_string;
573 $v=$urltop.$v; # url relative to top of site
575 $v =~ s/\"/&quot;/g; # since we quote with ""
576 substr($text, $v_offset, $v_len) = qq("$v");
579 $ret.=$text;
580 }, "tagname, tokenpos, text");
581 $p->parse($html);
582 $p->eof;
584 return $ret;
587 sub genfeed ($$$$$@) {
588 my $feedtype=shift;
589 my $feedurl=shift;
590 my $feeddesc=shift;
591 my $guid=shift;
592 my $page=shift;
593 my @pages=@_;
595 my $url=URI->new(encode_utf8(urlto($page,"",1)));
597 my $itemtemplate=template_depends($feedtype."item.tmpl", $page, blind_cache => 1);
598 my $content="";
599 my $lasttime = 0;
600 foreach my $p (@pages) {
601 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
602 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
604 $itemtemplate->param(
605 title => pagetitle(basename($p)),
606 url => $u,
607 permalink => $u,
608 cdate_822 => date_822($pagectime{$p}),
609 mdate_822 => date_822($pagemtime{$p}),
610 cdate_3339 => date_3339($pagectime{$p}),
611 mdate_3339 => date_3339($pagemtime{$p}),
614 if (exists $pagestate{$p}) {
615 if (exists $pagestate{$p}{meta}{guid}) {
616 eval q{use HTML::Entities};
617 $itemtemplate->param(guid => HTML::Entities::encode_numeric($pagestate{$p}{meta}{guid}));
620 if (exists $pagestate{$p}{meta}{updated}) {
621 $itemtemplate->param(mdate_822 => date_822($pagestate{$p}{meta}{updated}));
622 $itemtemplate->param(mdate_3339 => date_3339($pagestate{$p}{meta}{updated}));
626 if ($itemtemplate->query(name => "enclosure")) {
627 my $file=$pagesources{$p};
628 my $type=pagetype($file);
629 if (defined $type) {
630 $itemtemplate->param(content => $pcontent);
632 else {
633 my $size=(srcfile_stat($file))[8];
634 my $mime="unknown";
635 eval q{use File::MimeInfo};
636 if (! $@) {
637 $mime = mimetype($file);
639 $itemtemplate->param(
640 enclosure => $u,
641 type => $mime,
642 length => $size,
646 else {
647 $itemtemplate->param(content => $pcontent);
650 run_hooks(pagetemplate => sub {
651 shift->(page => $p, destpage => $page,
652 template => $itemtemplate);
655 $content.=$itemtemplate->output;
656 $itemtemplate->clear_params;
658 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
661 my $template=template_depends($feedtype."page.tmpl", $page, blind_cache => 1);
662 $template->param(
663 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
664 wikiname => $config{wikiname},
665 pageurl => $url,
666 content => $content,
667 feeddesc => $feeddesc,
668 guid => $guid,
669 feeddate => date_3339($lasttime),
670 feedurl => $feedurl,
671 version => $IkiWiki::version,
673 run_hooks(pagetemplate => sub {
674 shift->(page => $page, destpage => $page,
675 template => $template);
678 return $template->output;
681 sub pingurl (@) {
682 return unless @{$config{pingurl}} && %toping;
684 eval q{require RPC::XML::Client};
685 if ($@) {
686 debug(gettext("RPC::XML::Client not found, not pinging"));
687 return;
690 # daemonize here so slow pings don't slow down wiki updates
691 defined(my $pid = fork) or error("Can't fork: $!");
692 return if $pid;
693 chdir '/';
694 POSIX::setsid() or error("Can't start a new session: $!");
695 open STDIN, '/dev/null';
696 open STDOUT, '>/dev/null';
697 open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
699 # Don't need to keep a lock on the wiki as a daemon.
700 IkiWiki::unlockwiki();
702 foreach my $page (keys %toping) {
703 my $title=pagetitle(basename($page), 0);
704 my $url=urlto($page, "", 1);
705 foreach my $pingurl (@{$config{pingurl}}) {
706 debug("Pinging $pingurl for $page");
707 eval {
708 my $client = RPC::XML::Client->new($pingurl);
709 my $req = RPC::XML::request->new('weblogUpdates.ping',
710 $title, $url);
711 my $res = $client->send_request($req);
712 if (! ref $res) {
713 error("Did not receive response to ping");
715 my $r=$res->value;
716 if (! exists $r->{flerror} || $r->{flerror}) {
717 error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
720 if ($@) {
721 error "Ping failed: $@";
726 exit 0; # daemon done
730 sub rootpage (@) {
731 my %params=@_;
733 my $rootpage;
734 if (exists $params{rootpage}) {
735 $rootpage=bestlink($params{page}, $params{rootpage});
736 if (!length $rootpage) {
737 $rootpage=$params{rootpage};
740 else {
741 $rootpage=$params{page};
743 return $rootpage;