]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/inline.pm
Merge branch 'master' of ssh://git.ikiwiki.info/srv/git/ikiwiki.info
[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 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);
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         }
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};
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} && ! exists $params{pagenames}) {
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;
188         if (exists $params{pagenames}) {
189                 foreach my $p (qw(sort pages)) {
190                         if (exists $params{$p}) {
191                                 error sprintf(gettext("the %s and %s parameters cannot be used together"),
192                                         "pagenames", $p);
193                         }
194                 }
196                 @list = map { bestlink($params{page}, $_) }
197                         split ' ', $params{pagenames};
199                 if (yesno($params{reverse})) {
200                         @list=reverse(@list);
201                 }
203                 foreach my $p (@list) {
204                         add_depends($params{page}, $p, deptype($quick ? "presence" : "content"));
205                 }
206         }
207         else {
208                 my $num=0;
209                 if ($params{show}) {
210                         $num=$params{show};
211                 }
212                 if ($params{feedshow} && $num < $params{feedshow}) {
213                         $num=$params{feedshow};
214                 }
215                 if ($params{skip}) {
216                         $num+=$params{skip};
217                 }
219                 @list = pagespec_match_list($params{page}, $params{pages},
220                         deptype => deptype($quick ? "presence" : "content"),
221                         filter => sub { $_[0] eq $params{page} },
222                         sort => exists $params{sort} ? $params{sort} : "age",
223                         reverse => yesno($params{reverse}),
224                         num => $num,
225                 );
226         }
228         if (exists $params{skip}) {
229                 @list=@list[$params{skip} .. $#list];
230         }
231         
232         my @feedlist;
233         if ($feeds) {
234                 if (exists $params{feedshow} &&
235                     $params{feedshow} && @list > $params{feedshow}) {
236                         @feedlist=@list[0..$params{feedshow} - 1];
237                 }
238                 else {
239                         @feedlist=@list;
240                 }
241         }
242         
243         if ($params{show} && @list > $params{show}) {
244                 @list=@list[0..$params{show} - 1];
245         }
247         if ($feeds && exists $params{feedpages}) {
248                 @feedlist = pagespec_match_list(
249                         $params{page}, "($params{pages}) and ($params{feedpages})",
250                         deptype => deptype($quick ? "presence" : "content"),
251                         list => \@feedlist,
252                 );
253         }
255         my ($feedbase, $feednum);
256         if ($feeds) {
257                 # Ensure that multiple feeds on a page go to unique files.
258                 
259                 # Feedfile can lead to conflicts if usedirs is not enabled,
260                 # so avoid supporting it in that case.
261                 delete $params{feedfile} if ! $config{usedirs};
262                 # Tight limits on legal feedfiles, to avoid security issues
263                 # and conflicts.
264                 if (defined $params{feedfile}) {
265                         if ($params{feedfile} =~ /\// ||
266                             $params{feedfile} !~ /$config{wiki_file_regexp}/) {
267                                 error("illegal feedfile");
268                         }
269                         $params{feedfile}=possibly_foolish_untaint($params{feedfile});
270                 }
271                 $feedbase=targetpage($params{destpage}, "", $params{feedfile});
273                 my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
274                 if (exists $knownfeeds{$feedid}) {
275                         $feednum=$knownfeeds{$feedid};
276                 }
277                 else {
278                         if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
279                                 if ($feeds) {
280                                         $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
281                                 }
282                         }
283                         else {
284                                 $feednum=$knownfeeds{$feedid}="";
285                                 if ($feeds) {
286                                         $page_numfeeds{$params{destpage}}{$feedbase}=1;
287                                 }
288                         }
289                 }
290         }
292         my $rssurl=abs2rel($feedbase."rss".$feednum, dirname(htmlpage($params{destpage}))) if $feeds && $rss;
293         my $atomurl=abs2rel($feedbase."atom".$feednum, dirname(htmlpage($params{destpage}))) if $feeds && $atom;
295         my $ret="";
297         if (length $config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
298             (exists $params{postform} && yesno($params{postform}))) &&
299             IkiWiki->can("cgi_editpage")) {
300                 # Add a blog post form, with feed buttons.
301                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
302                 $formtemplate->param(cgiurl => $config{cgiurl});
303                 $formtemplate->param(rootpage => rootpage(%params));
304                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
305                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
306                 if (exists $params{postformtext}) {
307                         $formtemplate->param(postformtext =>
308                                 $params{postformtext});
309                 }
310                 else {
311                         $formtemplate->param(postformtext =>
312                                 gettext("Add a new post titled:"));
313                 }
314                 $ret.=$formtemplate->output;
315                 
316                 # The post form includes the feed buttons, so
317                 # emptyfeeds cannot be hidden.
318                 $emptyfeeds=1;
319         }
320         elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
321                 # Add feed buttons.
322                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
323                 $linktemplate->param(rssurl => $rssurl) if $rss;
324                 $linktemplate->param(atomurl => $atomurl) if $atom;
325                 $ret.=$linktemplate->output;
326         }
327         
328         if (! $feedonly) {
329                 require HTML::Template;
330                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
331                 if (! @params) {
332                         error sprintf(gettext("nonexistant template %s"), $params{template});
333                 }
334                 my $template=HTML::Template->new(@params) unless $raw;
335         
336                 foreach my $page (@list) {
337                         my $file = $pagesources{$page};
338                         my $type = pagetype($file);
339                         if (! $raw || ($raw && ! defined $type)) {
340                                 if (!($archive && $quick) &&
341                                     $template->query(name => 'content')) {
342                                         # Get the content before populating the
343                                         # template, since getting the content uses
344                                         # the same template if inlines are nested.
345                                         my $content=get_inline_content($page, $params{destpage});
346                                         $template->param(content => $content);
347                                 }
348                                 $template->param(pageurl => urlto($page, $params{destpage}));
349                                 $template->param(inlinepage => $page);
350                                 $template->param(title => pagetitle(basename($page)));
351                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
352                                 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
353                                 $template->param(first => 1) if $page eq $list[0];
354                                 $template->param(last => 1) if $page eq $list[$#list];
355         
356                                 if ($actions) {
357                                         my $file = $pagesources{$page};
358                                         my $type = pagetype($file);
359                                         if ($config{discussion}) {
360                                                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/ &&
361                                                     (length $config{cgiurl} ||
362                                                      exists $links{$page."/".$config{discussionpage}})) {
363                                                         $template->param(have_actions => 1);
364                                                         $template->param(discussionlink =>
365                                                                 htmllink($page,
366                                                                         $params{destpage},
367                                                                         $config{discussionpage},
368                                                                         noimageinline => 1,
369                                                                         forcesubpage => 1));
370                                                 }
371                                         }
372                                         if (length $config{cgiurl} && defined $type) {
373                                                 $template->param(have_actions => 1);
374                                                 $template->param(editurl => cgiurl(do => "edit", page => $page));
375                                         }
376                                 }
377         
378                                 run_hooks(pagetemplate => sub {
379                                         shift->(page => $page, destpage => $params{destpage},
380                                                 template => $template,);
381                                 });
382         
383                                 $ret.=$template->output;
384                                 $template->clear_params;
385                         }
386                         else {
387                                 if (defined $type) {
388                                         $ret.="\n".
389                                               linkify($page, $params{destpage},
390                                               preprocess($page, $params{destpage},
391                                               filter($page, $params{destpage},
392                                               readfile(srcfile($file)))));
393                                 }
394                         }
395                 }
396         }
397         
398         if ($feeds && ($emptyfeeds || @feedlist)) {
399                 if ($rss) {
400                         my $rssp=$feedbase."rss".$feednum;
401                         will_render($params{destpage}, $rssp);
402                         if (! $params{preview}) {
403                                 writefile($rssp, $config{destdir},
404                                         genfeed("rss",
405                                                 $config{url}."/".$rssp, $desc, $params{guid}, $params{destpage}, @feedlist));
406                                 $toping{$params{destpage}}=1 unless $config{rebuild};
407                                 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$desc (RSS)" href="$rssurl" />};
408                         }
409                 }
410                 if ($atom) {
411                         my $atomp=$feedbase."atom".$feednum;
412                         will_render($params{destpage}, $atomp);
413                         if (! $params{preview}) {
414                                 writefile($atomp, $config{destdir},
415                                         genfeed("atom", $config{url}."/".$atomp, $desc, $params{guid}, $params{destpage}, @feedlist));
416                                 $toping{$params{destpage}}=1 unless $config{rebuild};
417                                 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$desc (Atom)" href="$atomurl" />};
418                         }
419                 }
420         }
421         
422         return $ret if $raw || $nested;
423         push @inline, $ret;
424         return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
427 sub pagetemplate_inline (@) {
428         my %params=@_;
429         my $page=$params{page};
430         my $template=$params{template};
432         $template->param(feedlinks => $feedlinks{$page})
433                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
436 sub get_inline_content ($$) {
437         my $page=shift;
438         my $destpage=shift;
439         
440         my $file=$pagesources{$page};
441         my $type=pagetype($file);
442         if (defined $type) {
443                 $nested++;
444                 my $ret=htmlize($page, $destpage, $type,
445                        linkify($page, $destpage,
446                        preprocess($page, $destpage,
447                        filter($page, $destpage,
448                        readfile(srcfile($file))))));
449                 $nested--;
450                 return $ret;
451         }
452         else {
453                 return "";
454         }
457 sub date_822 ($) {
458         my $time=shift;
460         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
461         POSIX::setlocale(&POSIX::LC_TIME, "C");
462         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
463         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
464         return $ret;
467 sub date_3339 ($) {
468         my $time=shift;
470         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
471         POSIX::setlocale(&POSIX::LC_TIME, "C");
472         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
473         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
474         return $ret;
477 sub absolute_urls ($$) {
478         # sucky sub because rss sucks
479         my $content=shift;
480         my $baseurl=shift;
482         my $url=$baseurl;
483         $url=~s/[^\/]+$//;
485         # what is the non path part of the url?
486         my $top_uri = URI->new($url);
487         $top_uri->path_query(""); # reset the path
488         my $urltop = $top_uri->as_string;
490         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
491         # relative to another wiki page
492         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)([^\/][^"]*)"/$1 href="$url$2"/mig;
493         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)([^\/][^"]*)"/$1 src="$url$2"/mig;
494         # relative to the top of the site
495         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)(\/[^"]*)"/$1 href="$urltop$2"/mig;
496         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)(\/[^"]*)"/$1 src="$urltop$2"/mig;
497         return $content;
500 sub genfeed ($$$$$@) {
501         my $feedtype=shift;
502         my $feedurl=shift;
503         my $feeddesc=shift;
504         my $guid=shift;
505         my $page=shift;
506         my @pages=@_;
507         
508         my $url=URI->new(encode_utf8(urlto($page,"",1)));
509         
510         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
511         my $content="";
512         my $lasttime = 0;
513         foreach my $p (@pages) {
514                 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
515                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
517                 $itemtemplate->param(
518                         title => pagetitle(basename($p)),
519                         url => $u,
520                         permalink => $u,
521                         cdate_822 => date_822($pagectime{$p}),
522                         mdate_822 => date_822($pagemtime{$p}),
523                         cdate_3339 => date_3339($pagectime{$p}),
524                         mdate_3339 => date_3339($pagemtime{$p}),
525                 );
527                 if (exists $pagestate{$p}) {
528                         if (exists $pagestate{$p}{meta}{guid}) {
529                                 $itemtemplate->param(guid => $pagestate{$p}{meta}{guid});
530                         }
532                         if (exists $pagestate{$p}{meta}{updated}) {
533                                 $itemtemplate->param(mdate_822 => date_822($pagestate{$p}{meta}{updated}));
534                                 $itemtemplate->param(mdate_3339 => date_3339($pagestate{$p}{meta}{updated}));
535                         }
536                 }
538                 if ($itemtemplate->query(name => "enclosure")) {
539                         my $file=$pagesources{$p};
540                         my $type=pagetype($file);
541                         if (defined $type) {
542                                 $itemtemplate->param(content => $pcontent);
543                         }
544                         else {
545                                 my $size=(srcfile_stat($file))[8];
546                                 my $mime="unknown";
547                                 eval q{use File::MimeInfo};
548                                 if (! $@) {
549                                         $mime = mimetype($file);
550                                 }
551                                 $itemtemplate->param(
552                                         enclosure => $u,
553                                         type => $mime,
554                                         length => $size,
555                                 );
556                         }
557                 }
558                 else {
559                         $itemtemplate->param(content => $pcontent);
560                 }
562                 run_hooks(pagetemplate => sub {
563                         shift->(page => $p, destpage => $page,
564                                 template => $itemtemplate);
565                 });
567                 $content.=$itemtemplate->output;
568                 $itemtemplate->clear_params;
570                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
571         }
573         my $template=template($feedtype."page.tmpl", blind_cache => 1);
574         $template->param(
575                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
576                 wikiname => $config{wikiname},
577                 pageurl => $url,
578                 content => $content,
579                 feeddesc => $feeddesc,
580                 guid => $guid,
581                 feeddate => date_3339($lasttime),
582                 feedurl => $feedurl,
583                 version => $IkiWiki::version,
584         );
585         run_hooks(pagetemplate => sub {
586                 shift->(page => $page, destpage => $page,
587                         template => $template);
588         });
589         
590         return $template->output;
593 sub pingurl (@) {
594         return unless @{$config{pingurl}} && %toping;
596         eval q{require RPC::XML::Client};
597         if ($@) {
598                 debug(gettext("RPC::XML::Client not found, not pinging"));
599                 return;
600         }
602         # daemonize here so slow pings don't slow down wiki updates
603         defined(my $pid = fork) or error("Can't fork: $!");
604         return if $pid;
605         chdir '/';
606         POSIX::setsid() or error("Can't start a new session: $!");
607         open STDIN, '/dev/null';
608         open STDOUT, '>/dev/null';
609         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
611         # Don't need to keep a lock on the wiki as a daemon.
612         IkiWiki::unlockwiki();
614         foreach my $page (keys %toping) {
615                 my $title=pagetitle(basename($page), 0);
616                 my $url=urlto($page, "", 1);
617                 foreach my $pingurl (@{$config{pingurl}}) {
618                         debug("Pinging $pingurl for $page");
619                         eval {
620                                 my $client = RPC::XML::Client->new($pingurl);
621                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
622                                         $title, $url);
623                                 my $res = $client->send_request($req);
624                                 if (! ref $res) {
625                                         error("Did not receive response to ping");
626                                 }
627                                 my $r=$res->value;
628                                 if (! exists $r->{flerror} || $r->{flerror}) {
629                                         error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
630                                 }
631                         };
632                         if ($@) {
633                                 error "Ping failed: $@";
634                         }
635                 }
636         }
638         exit 0; # daemon done
642 sub rootpage (@) {
643         my %params=@_;
645         my $rootpage;
646         if (exists $params{rootpage}) {
647                 $rootpage=bestlink($params{page}, $params{rootpage});
648                 if (!length $rootpage) {
649                         $rootpage=$params{rootpage};
650                 }
651         }
652         else {
653                 $rootpage=$params{page};
654         }
655         return $rootpage;