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