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