* Optimise displaytime, trimming maybe 6% off the build time.
[ikiwiki.git] / IkiWiki / Plugin / inline.pm
1 #!/usr/bin/perl
2 # Page inlining and blogging.
3 package IkiWiki::Plugin::inline;
4
5 use warnings;
6 use strict;
7 use IkiWiki 1.00;
8 use URI;
9
10 sub import { #{{{
11         hook(type => "getopt", id => "inline", call => \&getopt);
12         hook(type => "checkconfig", id => "inline", call => \&checkconfig);
13         hook(type => "preprocess", id => "inline", 
14                 call => \&IkiWiki::preprocess_inline);
15         hook(type => "pagetemplate", id => "inline",
16                 call => \&IkiWiki::pagetemplate_inline);
17         # Hook to change to do pinging since it's called late.
18         # This ensures each page only pings once and prevents slow
19         # pings interrupting page builds.
20         hook(type => "change", id => "inline", 
21                 call => \&IkiWiki::pingurl);
22 } # }}}
23
24 sub getopt () { #{{{
25         eval q{use Getopt::Long};
26         error($@) if $@;
27         Getopt::Long::Configure('pass_through');
28         GetOptions(
29                 "rss!" => \$config{rss},
30                 "atom!" => \$config{atom},
31         );
32 }
33
34 sub checkconfig () { #{{{
35         if (($config{rss} || $config{atom}) && ! length $config{url}) {
36                 error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
37         }
38         if ($config{rss}) {
39                 push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
40         }
41         if ($config{atom}) {
42                 push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
43         }
44 } #}}}
45
46 # Back to ikiwiki namespace for the rest, this code is very much
47 # internal to ikiwiki even though it's separated into a plugin.
48 package IkiWiki;
49
50 my %toping;
51 my %feedlinks;
52
53 sub yesno ($) { #{{{
54         my $val=shift;
55         return (defined $val && lc($val) eq "yes");
56 } #}}}
57
58 sub preprocess_inline (@) { #{{{
59         my %params=@_;
60         
61         if (! exists $params{pages}) {
62                 return "";
63         }
64         my $raw=yesno($params{raw});
65         my $archive=yesno($params{archive});
66         my $rss=($config{rss} && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
67         my $atom=($config{atom} && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
68         my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
69         my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
70         $feeds=0 if $params{preview};
71         if (! exists $params{show} && ! $archive) {
72                 $params{show}=10;
73         }
74         my $desc;
75         if (exists $params{description}) {
76                 $desc = $params{description} 
77         } else {
78                 $desc = $config{wikiname};
79         }
80         my $actions=yesno($params{actions});
81         if (exists $params{template}) {
82                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
83         }
84         else {
85                 $params{template} = $archive ? "archivepage" : "inlinepage";
86         }
87
88         my @list;
89         foreach my $page (keys %pagesources) {
90                 next if $page eq $params{page};
91                 if (pagespec_match($page, $params{pages}, $params{page})) {
92                         push @list, $page;
93                 }
94         }
95
96         if (exists $params{sort} && $params{sort} eq 'title') {
97                 @list=sort @list;
98         }
99         elsif (exists $params{sort} && $params{sort} eq 'mtime') {
100                 @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
101         }
102         elsif (! exists $params{sort} || $params{sort} eq 'age') {
103                 @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
104         }
105         else {
106                 return sprintf(gettext("unknown sort type %s"), $params{sort});
107         }
108
109         if (yesno($params{reverse})) {
110                 @list=reverse(@list);
111         }
112
113         if (exists $params{skip}) {
114                 @list=@list[$params{skip} .. scalar @list - 1];
115         }
116         
117         if ($params{show} && @list > $params{show}) {
118                 @list=@list[0..$params{show} - 1];
119         }
120
121         add_depends($params{page}, $params{pages});
122         # Explicitly add all currently displayed pages as dependencies, so
123         # that if they are removed or otherwise changed, the inline will be
124         # sure to be updated.
125         add_depends($params{page}, join(" or ", @list));
126
127         my $rssurl=basename(rsspage($params{page}));
128         my $atomurl=basename(atompage($params{page}));
129         my $ret="";
130
131         if ($config{cgiurl} && (exists $params{rootpage} ||
132                         (exists $params{postform} && yesno($params{postform})))) {
133                 # Add a blog post form, with feed buttons.
134                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
135                 $formtemplate->param(cgiurl => $config{cgiurl});
136                 $formtemplate->param(rootpage => 
137                         exists $params{rootpage} ? $params{rootpage} : $params{page});
138                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
139                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
140                 $ret.=$formtemplate->output;
141         }
142         elsif ($feeds) {
143                 # Add feed buttons.
144                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
145                 $linktemplate->param(rssurl => $rssurl) if $rss;
146                 $linktemplate->param(atomurl => $atomurl) if $atom;
147                 $ret.=$linktemplate->output;
148         }
149         
150         my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
151         if (! @params) {
152                 return sprintf(gettext("nonexistant template %s"), $params{template});
153         }
154         my $template=HTML::Template->new(@params) unless $raw;
155         
156         foreach my $page (@list) {
157                 my $file = $pagesources{$page};
158                 my $type = pagetype($file);
159                 if (! $raw || ($raw && ! defined $type)) {
160                         unless ($archive && $quick) {
161                                 # Get the content before populating the
162                                 # template, since getting the content uses
163                                 # the same template if inlines are nested.
164                                 my $content=get_inline_content($page, $params{destpage});
165                                 $template->param(content => $content);
166                         }
167                         $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
168                         $template->param(title => pagetitle(basename($page)));
169                         $template->param(ctime => displaytime($pagectime{$page}));
170
171                         if ($actions) {
172                                 my $file = $pagesources{$page};
173                                 my $type = pagetype($file);
174                                 if ($config{discussion}) {
175                                         my $discussionlink=gettext("discussion");
176                                         if ($page !~ /.*\/\Q$discussionlink\E$/ &&
177                                             (length $config{cgiurl} ||
178                                              exists $links{$page."/".$discussionlink})) {
179                                                 $template->param(have_actions => 1);
180                                                 $template->param(discussionlink =>
181                                                         htmllink($page,
182                                                                 $params{page},
183                                                                 gettext("Discussion"),
184                                                                 noimageinline => 1,
185                                                                 forcesubpage => 1));
186                                         }
187                                 }
188                                 if (length $config{cgiurl} && defined $type) {
189                                         $template->param(have_actions => 1);
190                                         $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
191                                 }
192                         }
193
194                         run_hooks(pagetemplate => sub {
195                                 shift->(page => $page, destpage => $params{page},
196                                         template => $template,);
197                         });
198
199                         $ret.=$template->output;
200                         $template->clear_params;
201                 }
202                 else {
203                         if (defined $type) {
204                                 $ret.="\n".
205                                       linkify($page, $params{page},
206                                       preprocess($page, $params{page},
207                                       filter($page,
208                                       readfile(srcfile($file)))));
209                         }
210                 }
211         }
212         
213         if ($feeds) {
214                 if (exists $params{feedshow} && @list > $params{feedshow}) {
215                         @list=@list[0..$params{feedshow} - 1];
216                 }
217         
218                 if ($rss) {
219                         my $rssp=rsspage($params{page});
220                         will_render($params{page}, $rssp);
221                         writefile($rssp, $config{destdir},
222                                 genfeed("rss", $rssurl, $desc, $params{page}, @list));
223                         $toping{$params{page}}=1 unless $config{rebuild};
224                         $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/rss+xml" title="RSS" href="$rssurl" />};
225                 }
226                 if ($atom) {
227                         my $atomp=atompage($params{page});
228                         will_render($params{page}, $atomp);
229                         writefile($atomp, $config{destdir},
230                                 genfeed("atom", $atomurl, $desc, $params{page}, @list));
231                         $toping{$params{page}}=1 unless $config{rebuild};
232                         $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/atom+xml" title="Atom" href="$atomurl" />};
233                 }
234         }
235         
236         return $ret;
237 } #}}}
238
239 sub pagetemplate_inline (@) { #{{{
240         my %params=@_;
241         my $page=$params{page};
242         my $template=$params{template};
243
244         $template->param(feedlinks => $feedlinks{$page})
245                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
246 } #}}}
247
248 sub get_inline_content ($$) { #{{{
249         my $page=shift;
250         my $destpage=shift;
251         
252         my $file=$pagesources{$page};
253         my $type=pagetype($file);
254         if (defined $type) {
255                 return htmlize($page, $type,
256                        linkify($page, $destpage,
257                        preprocess($page, $destpage,
258                        filter($page,
259                        readfile(srcfile($file))))));
260         }
261         else {
262                 return "";
263         }
264 } #}}}
265
266 sub date_822 ($) { #{{{
267         my $time=shift;
268
269         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
270         POSIX::setlocale(&POSIX::LC_TIME, "C");
271         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
272         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
273         return $ret;
274 } #}}}
275
276 sub date_3339 ($) { #{{{
277         my $time=shift;
278
279         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
280         POSIX::setlocale(&POSIX::LC_TIME, "C");
281         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", localtime($time));
282         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
283         return $ret;
284 } #}}}
285
286 sub absolute_urls ($$) { #{{{
287         # sucky sub because rss sucks
288         my $content=shift;
289         my $baseurl=shift;
290
291         my $url=$baseurl;
292         $url=~s/[^\/]+$//;
293         
294         $content=~s/(<a(?:\s+(?:class|id)="?\w+"?)?)\s+href="(#[^"]+)"/$1 href="$baseurl$2"/ig;
295         $content=~s/(<a(?:\s+(?:class|id)="?\w+"?)?)\s+href="(?!\w+:\/\/)([^"]+)"/$1 href="$url$2"/ig;
296         $content=~s/(<img(?:\s+(?:class|id)="?\w+"?)?)\s+src="(?!\w+:\/\/)([^"]+)"/$1 src="$url$2"/ig;
297         return $content;
298 } #}}}
299
300 sub rsspage ($) { #{{{
301         return targetpage(shift, "rss");
302 } #}}}
303
304 sub atompage ($) { #{{{
305         return targetpage(shift, "atom");
306 } #}}}
307
308 sub genfeed ($$$$@) { #{{{
309         my $feedtype=shift;
310         my $feedurl=shift;
311         my $feeddesc=shift;
312         my $page=shift;
313         my @pages=@_;
314         
315         my $url=URI->new(encode_utf8($config{url}."/".htmlpage($page)));
316         
317         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
318         my $content="";
319         my $lasttime = 0;
320         foreach my $p (@pages) {
321                 my $u=URI->new(encode_utf8($config{url}."/".htmlpage($p)));
322                 
323                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
324
325                 $itemtemplate->param(
326                         title => pagetitle(basename($p), 1),
327                         url => $u,
328                         permalink => $u,
329                         date_822 => date_822($pagectime{$p}),
330                         date_3339 => date_3339($pagectime{$p}),
331                 );
332
333                 if ($itemtemplate->query(name => "enclosure")) {
334                         my $file=$pagesources{$p};
335                         my $type=pagetype($file);
336                         if (defined $type) {
337                                 $itemtemplate->param(content => $pcontent);
338                         }
339                         else {
340                                 my ($a, $b, $c, $d, $e, $f, $g, $size) = stat(srcfile($file));
341                                 my $mime="unknown";
342                                 eval q{use File::MimeInfo};
343                                 if (! $@) {
344                                         $mime = mimetype($file);
345                                 }
346                                 $itemtemplate->param(
347                                         enclosure => $u,
348                                         type => $mime,
349                                         length => $size,
350                                 );
351                         }
352                 }
353                 else {
354                         $itemtemplate->param(content => $pcontent);
355                 }
356
357                 run_hooks(pagetemplate => sub {
358                         shift->(page => $p, destpage => $page,
359                                 template => $itemtemplate);
360                 });
361
362                 $content.=$itemtemplate->output;
363                 $itemtemplate->clear_params;
364
365                 $lasttime = $pagectime{$p} if $pagectime{$p} > $lasttime;
366         }
367
368         my $template=template($feedtype."page.tmpl", blind_cache => 1);
369         $template->param(
370                 title => $page ne "index" ? pagetitle($page, 1) : $config{wikiname},
371                 wikiname => $config{wikiname},
372                 pageurl => $url,
373                 content => $content,
374                 feeddesc => $feeddesc,
375                 feeddate => date_3339($lasttime),
376                 feedurl => $feedurl,
377                 version => $IkiWiki::version,
378         );
379         run_hooks(pagetemplate => sub {
380                 shift->(page => $page, destpage => $page,
381                         template => $template);
382         });
383         
384         return $template->output;
385 } #}}}
386
387 sub pingurl (@) { #{{{
388         return unless @{$config{pingurl}} && %toping;
389
390         eval q{require RPC::XML::Client};
391         if ($@) {
392                 debug(gettext("RPC::XML::Client not found, not pinging"));
393                 return;
394         }
395
396         # daemonize here so slow pings don't slow down wiki updates
397         defined(my $pid = fork) or error("Can't fork: $!");
398         return if $pid;
399         chdir '/';
400         setsid() or error("Can't start a new session: $!");
401         open STDIN, '/dev/null';
402         open STDOUT, '>/dev/null';
403         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
404
405         # Don't need to keep a lock on the wiki as a daemon.
406         IkiWiki::unlockwiki();
407
408         foreach my $page (keys %toping) {
409                 my $title=pagetitle(basename($page), 0);
410                 my $url="$config{url}/".htmlpage($page);
411                 foreach my $pingurl (@{$config{pingurl}}) {
412                         debug("Pinging $pingurl for $page");
413                         eval {
414                                 my $client = RPC::XML::Client->new($pingurl);
415                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
416                                         $title, $url);
417                                 my $res = $client->send_request($req);
418                                 if (! ref $res) {
419                                         debug("Did not receive response to ping");
420                                 }
421                                 my $r=$res->value;
422                                 if (! exists $r->{flerror} || $r->{flerror}) {
423                                         debug("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
424                                 }
425                         };
426                         if ($@) {
427                                 debug "Ping failed: $@";
428                         }
429                 }
430         }
431
432         exit 0; # daemon done
433 } #}}}
434
435 1