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