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