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