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