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