]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/inline.pm
get rid of the [postcomment] hack
[git.ikiwiki.info.git] / IkiWiki / Plugin / inline.pm
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 2.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);
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);
30 } # }}}
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                 },      
44         );
45 } #}}}
47 sub getsetup () { #{{{
48         return
49                 plugin => {
50                         safe => 1,
51                         rebuild => undef,
52                 },
53                 rss => {
54                         type => "boolean",
55                         example => 0,
56                         description => "enable rss feeds by default?",
57                         safe => 1,
58                         rebuild => 1,
59                 },
60                 atom => {
61                         type => "boolean",
62                         example => 0,
63                         description => "enable atom feeds by default?",
64                         safe => 1,
65                         rebuild => 1,
66                 },
67                 allowrss => {
68                         type => "boolean",
69                         example => 0,
70                         description => "allow rss feeds to be used?",
71                         safe => 1,
72                         rebuild => 1,
73                 },
74                 allowatom => {
75                         type => "boolean",
76                         example => 0,
77                         description => "allow atom feeds to be used?",
78                         safe => 1,
79                         rebuild => 1,
80                 },
81                 pingurl => {
82                         type => "string",
83                         example => "http://rpc.technorati.com/rpc/ping",
84                         description => "urls to ping (using XML-RPC) on feed update",
85                         safe => 1,
86                         rebuild => 0,
87                 },
88 } #}}}
90 sub checkconfig () { #{{{
91         if (($config{rss} || $config{atom}) && ! length $config{url}) {
92                 error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
93         }
94         if ($config{rss}) {
95                 push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
96         }
97         if ($config{atom}) {
98                 push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
99         }
100         if (! exists $config{pingurl}) {
101                 $config{pingurl}=[];
102         }
103 } #}}}
105 sub format (@) { #{{{
106         my %params=@_;
108         # Fill in the inline content generated earlier. This is actually an
109         # optimisation.
110         $params{content}=~s{<div class="inline" id="([^"]+)"></div>}{
111                 delete @inline[$1,]
112         }eg;
113         return $params{content};
114 } #}}}
116 sub sessioncgi ($$) { #{{{
117         my $q=shift;
118         my $session=shift;
120         if ($q->param('do') eq 'blog') {
121                 my $page=titlepage(decode_utf8($q->param('title')));
122                 $page=~s/(\/)/"__".ord($1)."__"/eg; # don't create subdirs
123                 # if the page already exists, munge it to be unique
124                 my $from=$q->param('from');
125                 my $add="";
126                 while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
127                         $add=1 unless length $add;
128                         $add++;
129                 }
130                 $q->param('page', $page.$add);
131                 # now go create the page
132                 $q->param('do', 'create');
133                 # make sure the editpage plugin in loaded
134                 if (IkiWiki->can("cgi_editpage")) {
135                         IkiWiki::cgi_editpage($q, $session);
136                 }
137                 else {
138                         error(gettext("page editing not allowed"));
139                 }
140                 exit;
141         }
144 # Back to ikiwiki namespace for the rest, this code is very much
145 # internal to ikiwiki even though it's separated into a plugin.
146 package IkiWiki;
148 my %toping;
149 my %feedlinks;
151 sub preprocess_inline (@) { #{{{
152         my %params=@_;
153         
154         if (! exists $params{pages}) {
155                 error gettext("missing pages parameter");
156         }
157         my $raw=yesno($params{raw});
158         my $archive=yesno($params{archive});
159         my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
160         my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
161         my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
162         my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
163         my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
164         my $feedonly=yesno($params{feedonly});
165         if (! exists $params{show} && ! $archive) {
166                 $params{show}=10;
167         }
168         if (! exists $params{feedshow} && exists $params{show}) {
169                 $params{feedshow}=$params{show};
170         }
171         my $desc;
172         if (exists $params{description}) {
173                 $desc = $params{description} 
174         }
175         else {
176                 $desc = $config{wikiname};
177         }
178         my $actions=yesno($params{actions});
179         if (exists $params{template}) {
180                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
181         }
182         else {
183                 $params{template} = $archive ? "archivepage" : "inlinepage";
184         }
186         my @list;
187         foreach my $page (keys %pagesources) {
188                 next if $page eq $params{page};
189                 if (pagespec_match($page, $params{pages}, location => $params{page})) {
190                         push @list, $page;
191                 }
192         }
194         if (exists $params{sort} && $params{sort} eq 'title') {
195                 @list=sort { pagetitle(basename($a)) cmp pagetitle(basename($b)) } @list;
196         }
197         elsif (exists $params{sort} && $params{sort} eq 'mtime') {
198                 @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
199         }
200         elsif (! exists $params{sort} || $params{sort} eq 'age') {
201                 @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
202         }
203         else {
204                 error sprintf(gettext("unknown sort type %s"), $params{sort});
205         }
207         if (yesno($params{reverse})) {
208                 @list=reverse(@list);
209         }
211         if (exists $params{skip}) {
212                 @list=@list[$params{skip} .. scalar @list - 1];
213         }
214         
215         my @feedlist;
216         if ($feeds) {
217                 if (exists $params{feedshow} &&
218                     $params{feedshow} && @list > $params{feedshow}) {
219                         @feedlist=@list[0..$params{feedshow} - 1];
220                 }
221                 else {
222                         @feedlist=@list;
223                 }
224         }
225         
226         if ($params{show} && @list > $params{show}) {
227                 @list=@list[0..$params{show} - 1];
228         }
230         add_depends($params{page}, $params{pages});
231         # Explicitly add all currently displayed pages as dependencies, so
232         # that if they are removed or otherwise changed, the inline will be
233         # sure to be updated.
234         add_depends($params{page}, join(" or ", $#list >= $#feedlist ? @list : @feedlist));
235         
236         if ($feeds && exists $params{feedpages}) {
237                 @feedlist=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @feedlist;
238         }
240         my ($feedbase, $feednum);
241         if ($feeds) {
242                 # Ensure that multiple feeds on a page go to unique files.
243                 
244                 # Feedfile can lead to conflicts if usedirs is not enabled,
245                 # so avoid supporting it in that case.
246                 delete $params{feedfile} if ! $config{usedirs};
247                 # Tight limits on legal feedfiles, to avoid security issues
248                 # and conflicts.
249                 if (defined $params{feedfile}) {
250                         if ($params{feedfile} =~ /\// ||
251                             $params{feedfile} !~ /$config{wiki_file_regexp}/) {
252                                 error("illegal feedfile");
253                         }
254                         $params{feedfile}=possibly_foolish_untaint($params{feedfile});
255                 }
256                 $feedbase=targetpage($params{destpage}, "", $params{feedfile});
258                 my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
259                 if (exists $knownfeeds{$feedid}) {
260                         $feednum=$knownfeeds{$feedid};
261                 }
262                 else {
263                         if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
264                                 if ($feeds) {
265                                         $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
266                                 }
267                         }
268                         else {
269                                 $feednum=$knownfeeds{$feedid}="";
270                                 if ($feeds) {
271                                         $page_numfeeds{$params{destpage}}{$feedbase}=1;
272                                 }
273                         }
274                 }
275         }
277         my $rssurl=basename($feedbase."rss".$feednum) if $feeds && $rss;
278         my $atomurl=basename($feedbase."atom".$feednum) if $feeds && $atom;
280         my $ret="";
282         if (length $config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
283             (exists $params{postform} && yesno($params{postform}))) &&
284             IkiWiki->can("cgi_editpage")) {
285                 # Add a blog post form, with feed buttons.
286                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
287                 $formtemplate->param(cgiurl => $config{cgiurl});
288                 my $rootpage;
289                 if (exists $params{rootpage}) {
290                         $rootpage=bestlink($params{page}, $params{rootpage});
291                         if (!length $rootpage) {
292                                 $rootpage=$params{rootpage};
293                         }
294                 }
295                 else {
296                         $rootpage=$params{page};
297                 }
298                 $formtemplate->param(rootpage => $rootpage);
299                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
300                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
301                 if (exists $params{postformtext}) {
302                         $formtemplate->param(postformtext =>
303                                 $params{postformtext});
304                 }
305                 else {
306                         $formtemplate->param(postformtext =>
307                                 gettext("Add a new post titled:"));
308                 }
309                 $ret.=$formtemplate->output;
310                 
311                 # The post form includes the feed buttons, so
312                 # emptyfeeds cannot be hidden.
313                 $emptyfeeds=1;
314         }
315         elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
316                 # Add feed buttons.
317                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
318                 $linktemplate->param(rssurl => $rssurl) if $rss;
319                 $linktemplate->param(atomurl => $atomurl) if $atom;
320                 $ret.=$linktemplate->output;
321         }
322         
323         if (! $feedonly) {
324                 require HTML::Template;
325                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
326                 if (! @params) {
327                         error sprintf(gettext("nonexistant template %s"), $params{template});
328                 }
329                 my $template=HTML::Template->new(@params) unless $raw;
330         
331                 foreach my $page (@list) {
332                         my $file = $pagesources{$page};
333                         my $type = pagetype($file);
334                         if (! $raw || ($raw && ! defined $type)) {
335                                 unless ($archive && $quick) {
336                                         # Get the content before populating the
337                                         # template, since getting the content uses
338                                         # the same template if inlines are nested.
339                                         my $content=get_inline_content($page, $params{destpage});
340                                         $template->param(content => $content);
341                                 }
342                                 $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
343                                 $template->param(title => pagetitle(basename($page)));
344                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
345                                 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
346                                 $template->param(first => 1) if $page eq $list[0];
347                                 $template->param(last => 1) if $page eq $list[$#list];
348         
349                                 if ($actions) {
350                                         my $file = $pagesources{$page};
351                                         my $type = pagetype($file);
352                                         if ($config{discussion}) {
353                                                 my $discussionlink=gettext("discussion");
354                                                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
355                                                     (length $config{cgiurl} ||
356                                                      exists $links{$page."/".$discussionlink})) {
357                                                         $template->param(have_actions => 1);
358                                                         $template->param(discussionlink =>
359                                                                 htmllink($page,
360                                                                         $params{destpage},
361                                                                         gettext("Discussion"),
362                                                                         noimageinline => 1,
363                                                                         forcesubpage => 1));
364                                                 }
365                                         }
366                                         if (length $config{cgiurl} && defined $type) {
367                                                 $template->param(have_actions => 1);
368                                                 $template->param(editurl => cgiurl(do => "edit", page => $page));
369                                         }
370                                 }
371         
372                                 run_hooks(pagetemplate => sub {
373                                         shift->(page => $page, destpage => $params{destpage},
374                                                 template => $template,);
375                                 });
376         
377                                 $ret.=$template->output;
378                                 $template->clear_params;
379                         }
380                         else {
381                                 if (defined $type) {
382                                         $ret.="\n".
383                                               linkify($page, $params{destpage},
384                                               preprocess($page, $params{destpage},
385                                               filter($page, $params{destpage},
386                                               readfile(srcfile($file)))));
387                                 }
388                         }
389                 }
390         }
391         
392         if ($feeds && ($emptyfeeds || @feedlist)) {
393                 if ($rss) {
394                         my $rssp=$feedbase."rss".$feednum;
395                         will_render($params{destpage}, $rssp);
396                         if (! $params{preview}) {
397                                 writefile($rssp, $config{destdir},
398                                         genfeed("rss",
399                                                 $config{url}."/".$rssp, $desc, $params{guid}, $params{destpage}, @feedlist));
400                                 $toping{$params{destpage}}=1 unless $config{rebuild};
401                                 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$desc (RSS)" href="$rssurl" />};
402                         }
403                 }
404                 if ($atom) {
405                         my $atomp=$feedbase."atom".$feednum;
406                         will_render($params{destpage}, $atomp);
407                         if (! $params{preview}) {
408                                 writefile($atomp, $config{destdir},
409                                         genfeed("atom", $config{url}."/".$atomp, $desc, $params{guid}, $params{destpage}, @feedlist));
410                                 $toping{$params{destpage}}=1 unless $config{rebuild};
411                                 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$desc (Atom)" href="$atomurl" />};
412                         }
413                 }
414         }
415         
416         return $ret if $raw || $nested;
417         push @inline, $ret;
418         return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
419 } #}}}
421 sub pagetemplate_inline (@) { #{{{
422         my %params=@_;
423         my $page=$params{page};
424         my $template=$params{template};
426         $template->param(feedlinks => $feedlinks{$page})
427                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
428 } #}}}
430 sub get_inline_content ($$) { #{{{
431         my $page=shift;
432         my $destpage=shift;
433         
434         my $file=$pagesources{$page};
435         my $type=pagetype($file);
436         if (defined $type) {
437                 $nested++;
438                 my $ret=htmlize($page, $destpage, $type,
439                        linkify($page, $destpage,
440                        preprocess($page, $destpage,
441                        filter($page, $destpage,
442                        readfile(srcfile($file))))));
443                 $nested--;
444                 return $ret;
445         }
446         else {
447                 return "";
448         }
449 } #}}}
451 sub date_822 ($) { #{{{
452         my $time=shift;
454         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
455         POSIX::setlocale(&POSIX::LC_TIME, "C");
456         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
457         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
458         return $ret;
459 } #}}}
461 sub date_3339 ($) { #{{{
462         my $time=shift;
464         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
465         POSIX::setlocale(&POSIX::LC_TIME, "C");
466         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
467         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
468         return $ret;
469 } #}}}
471 sub absolute_urls ($$) { #{{{
472         # sucky sub because rss sucks
473         my $content=shift;
474         my $baseurl=shift;
476         my $url=$baseurl;
477         $url=~s/[^\/]+$//;
479         # what is the non path part of the url?
480         my $top_uri = URI->new($url);
481         $top_uri->path_query(""); # reset the path
482         my $urltop = $top_uri->as_string;
484         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
485         # relative to another wiki page
486         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)([^\/][^"]*)"/$1 href="$url$2"/mig;
487         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)([^\/][^"]*)"/$1 src="$url$2"/mig;
488         # relative to the top of the site
489         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)(\/[^"]*)"/$1 href="$urltop$2"/mig;
490         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)(\/[^"]*)"/$1 src="$urltop$2"/mig;
491         return $content;
492 } #}}}
494 sub genfeed ($$$$$@) { #{{{
495         my $feedtype=shift;
496         my $feedurl=shift;
497         my $feeddesc=shift;
498         my $guid=shift;
499         my $page=shift;
500         my @pages=@_;
501         
502         my $url=URI->new(encode_utf8(urlto($page,"",1)));
503         
504         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
505         my $content="";
506         my $lasttime = 0;
507         foreach my $p (@pages) {
508                 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
509                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
511                 $itemtemplate->param(
512                         title => pagetitle(basename($p)),
513                         url => $u,
514                         permalink => $u,
515                         cdate_822 => date_822($pagectime{$p}),
516                         mdate_822 => date_822($pagemtime{$p}),
517                         cdate_3339 => date_3339($pagectime{$p}),
518                         mdate_3339 => date_3339($pagemtime{$p}),
519                 );
521                 if (exists $pagestate{$p} &&
522                     exists $pagestate{$p}{meta}{guid}) {
523                         $itemtemplate->param(guid => $pagestate{$p}{meta}{guid});
524                 }
526                 if ($itemtemplate->query(name => "enclosure")) {
527                         my $file=$pagesources{$p};
528                         my $type=pagetype($file);
529                         if (defined $type) {
530                                 $itemtemplate->param(content => $pcontent);
531                         }
532                         else {
533                                 my $size=(srcfile_stat($file))[8];
534                                 my $mime="unknown";
535                                 eval q{use File::MimeInfo};
536                                 if (! $@) {
537                                         $mime = mimetype($file);
538                                 }
539                                 $itemtemplate->param(
540                                         enclosure => $u,
541                                         type => $mime,
542                                         length => $size,
543                                 );
544                         }
545                 }
546                 else {
547                         $itemtemplate->param(content => $pcontent);
548                 }
550                 run_hooks(pagetemplate => sub {
551                         shift->(page => $p, destpage => $page,
552                                 template => $itemtemplate);
553                 });
555                 $content.=$itemtemplate->output;
556                 $itemtemplate->clear_params;
558                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
559         }
561         my $template=template($feedtype."page.tmpl", blind_cache => 1);
562         $template->param(
563                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
564                 wikiname => $config{wikiname},
565                 pageurl => $url,
566                 content => $content,
567                 feeddesc => $feeddesc,
568                 guid => $guid,
569                 feeddate => date_3339($lasttime),
570                 feedurl => $feedurl,
571                 version => $IkiWiki::version,
572         );
573         run_hooks(pagetemplate => sub {
574                 shift->(page => $page, destpage => $page,
575                         template => $template);
576         });
577         
578         return $template->output;
579 } #}}}
581 sub pingurl (@) { #{{{
582         return unless @{$config{pingurl}} && %toping;
584         eval q{require RPC::XML::Client};
585         if ($@) {
586                 debug(gettext("RPC::XML::Client not found, not pinging"));
587                 return;
588         }
590         # daemonize here so slow pings don't slow down wiki updates
591         defined(my $pid = fork) or error("Can't fork: $!");
592         return if $pid;
593         chdir '/';
594         POSIX::setsid() or error("Can't start a new session: $!");
595         open STDIN, '/dev/null';
596         open STDOUT, '>/dev/null';
597         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
599         # Don't need to keep a lock on the wiki as a daemon.
600         IkiWiki::unlockwiki();
602         foreach my $page (keys %toping) {
603                 my $title=pagetitle(basename($page), 0);
604                 my $url=urlto($page, "", 1);
605                 foreach my $pingurl (@{$config{pingurl}}) {
606                         debug("Pinging $pingurl for $page");
607                         eval {
608                                 my $client = RPC::XML::Client->new($pingurl);
609                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
610                                         $title, $url);
611                                 my $res = $client->send_request($req);
612                                 if (! ref $res) {
613                                         error("Did not receive response to ping");
614                                 }
615                                 my $r=$res->value;
616                                 if (! exists $r->{flerror} || $r->{flerror}) {
617                                         error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
618                                 }
619                         };
620                         if ($@) {
621                                 error "Ping failed: $@";
622                         }
623                 }
624         }
626         exit 0; # daemon done
627 } #}}}