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