]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/inline.pm
b28ad27a8e01c32a17d5fc979c3f9c2b85156b74
[git.ikiwiki.info.git] / IkiWiki / Plugin / inline.pm
1 #!/usr/bin/perl
2 # Page inlining and blogging.
3 package IkiWiki::Plugin::inline;
5 use warnings;
6 use strict;
7 use Encode;
8 use IkiWiki 2.00;
9 use URI;
11 my %knownfeeds;
12 my %page_numfeeds;
14 sub import { #{{{
15         hook(type => "getopt", id => "inline", call => \&getopt);
16         hook(type => "checkconfig", id => "inline", call => \&checkconfig);
17         hook(type => "sessioncgi", id => "skeleton", 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);
28 } # }}}
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 }
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 } #}}}
52 sub sessioncgi () { #{{{
53         my $q=shift;
54         my $session=shift;
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 }
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;
78 my %toping;
79 my %feedlinks;
81 sub yesno ($) { #{{{
82         my $val=shift;
83         return (defined $val && lc($val) eq "yes");
84 } #}}}
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         $feeds=0 if $params{preview};
99         my $feedonly=yesno($params{feedonly});
100         if (! exists $params{show} && ! $archive) {
101                 $params{show}=10;
102         }
103         my $desc;
104         if (exists $params{description}) {
105                 $desc = $params{description} 
106         } else {
107                 $desc = $config{wikiname};
108         }
109         my $actions=yesno($params{actions});
110         if (exists $params{template}) {
111                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
112         }
113         else {
114                 $params{template} = $archive ? "archivepage" : "inlinepage";
115         }
117         my @list;
118         foreach my $page (keys %pagesources) {
119                 next if $page eq $params{page};
120                 if (pagespec_match($page, $params{pages}, location => $params{page})) {
121                         push @list, $page;
122                 }
123         }
125         if (exists $params{sort} && $params{sort} eq 'title') {
126                 @list=sort @list;
127         }
128         elsif (exists $params{sort} && $params{sort} eq 'mtime') {
129                 @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
130         }
131         elsif (! exists $params{sort} || $params{sort} eq 'age') {
132                 @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
133         }
134         else {
135                 return sprintf(gettext("unknown sort type %s"), $params{sort});
136         }
138         if (yesno($params{reverse})) {
139                 @list=reverse(@list);
140         }
142         if (exists $params{skip}) {
143                 @list=@list[$params{skip} .. scalar @list - 1];
144         }
145         
146         if ($params{show} && @list > $params{show}) {
147                 @list=@list[0..$params{show} - 1];
148         }
150         add_depends($params{page}, $params{pages});
151         # Explicitly add all currently displayed pages as dependencies, so
152         # that if they are removed or otherwise changed, the inline will be
153         # sure to be updated.
154         add_depends($params{page}, join(" or ", @list));
155         
156         my $feednum="";
158         my $feedid=join("\0", map { $_."\0".$params{$_} } sort keys %params);
159         if (exists $knownfeeds{$feedid}) {
160                 $feednum=$knownfeeds{$feedid};
161         }
162         else {
163                 if (exists $page_numfeeds{$params{destpage}}) {
164                         if ($feeds) {
165                                 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}};
166                         }
167                 }
168                 else {
169                         $feednum=$knownfeeds{$feedid}="";
170                         if ($feeds) {
171                                 $page_numfeeds{$params{destpage}}=1;
172                         }
173                 }
174         }
176         if ($feeds) {
177                 my $rssurl=basename(rsspage($params{destpage}).$feednum);
178                 my $atomurl=basename(atompage($params{destpage}).$feednum);
179         }
180         my $ret="";
182         if ($config{cgiurl} && (exists $params{rootpage} ||
183                         (exists $params{postform} && yesno($params{postform})))) {
184                 # Add a blog post form, with feed buttons.
185                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
186                 $formtemplate->param(cgiurl => $config{cgiurl});
187                 $formtemplate->param(rootpage => 
188                         exists $params{rootpage} ? $params{rootpage} : $params{page});
189                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
190                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
191                 if (exists $params{postformtext}) {
192                         $formtemplate->param(postformtext =>
193                                 $params{postformtext});
194                 }
195                 else {
196                         $formtemplate->param(postformtext =>
197                                 gettext("Add a new post titled:"));
198                 }
199                 $ret.=$formtemplate->output;
200         }
201         elsif ($feeds) {
202                 # Add feed buttons.
203                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
204                 $linktemplate->param(rssurl => $rssurl) if $rss;
205                 $linktemplate->param(atomurl => $atomurl) if $atom;
206                 $ret.=$linktemplate->output;
207         }
208         
209         if (! $feedonly) {
210                 require HTML::Template;
211                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
212                 if (! @params) {
213                         return sprintf(gettext("nonexistant template %s"), $params{template});
214                 }
215                 my $template=HTML::Template->new(@params) unless $raw;
216         
217                 foreach my $page (@list) {
218                         my $file = $pagesources{$page};
219                         my $type = pagetype($file);
220                         if (! $raw || ($raw && ! defined $type)) {
221                                 unless ($archive && $quick) {
222                                         # Get the content before populating the
223                                         # template, since getting the content uses
224                                         # the same template if inlines are nested.
225                                         my $content=get_inline_content($page, $params{destpage});
226                                         $template->param(content => $content);
227                                 }
228                                 $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
229                                 $template->param(title => pagetitle(basename($page)));
230                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
231         
232                                 if ($actions) {
233                                         my $file = $pagesources{$page};
234                                         my $type = pagetype($file);
235                                         if ($config{discussion}) {
236                                                 my $discussionlink=gettext("discussion");
237                                                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
238                                                     (length $config{cgiurl} ||
239                                                      exists $links{$page."/".$discussionlink})) {
240                                                         $template->param(have_actions => 1);
241                                                         $template->param(discussionlink =>
242                                                                 htmllink($page,
243                                                                         $params{destpage},
244                                                                         gettext("Discussion"),
245                                                                         noimageinline => 1,
246                                                                         forcesubpage => 1));
247                                                 }
248                                         }
249                                         if (length $config{cgiurl} && defined $type) {
250                                                 $template->param(have_actions => 1);
251                                                 $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
252                                         }
253                                 }
254         
255                                 run_hooks(pagetemplate => sub {
256                                         shift->(page => $page, destpage => $params{destpage},
257                                                 template => $template,);
258                                 });
259         
260                                 $ret.=$template->output;
261                                 $template->clear_params;
262                         }
263                         else {
264                                 if (defined $type) {
265                                         $ret.="\n".
266                                               linkify($page, $params{destpage},
267                                               preprocess($page, $params{destpage},
268                                               filter($page, $params{destpage},
269                                               readfile(srcfile($file)))));
270                                 }
271                         }
272                 }
273         }
274         
275         if ($feeds) {
276                 if (exists $params{feedshow} && @list > $params{feedshow}) {
277                         @list=@list[0..$params{feedshow} - 1];
278                 }
279                 if (exists $params{feedpages}) {
280                         @list=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @list;
281                 }
282         
283                 if ($rss) {
284                         my $rssp=rsspage($params{destpage}).$feednum;
285                         will_render($params{destpage}, $rssp);
286                         writefile($rssp, $config{destdir},
287                                 genfeed("rss", $rssurl, $desc, $params{destpage}, @list));
288                         $toping{$params{destpage}}=1 unless $config{rebuild};
289                         $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/rss+xml" title="RSS" href="$rssurl" />};
290                 }
291                 if ($atom) {
292                         my $atomp=atompage($params{destpage}).$feednum;
293                         will_render($params{destpage}, $atomp);
294                         writefile($atomp, $config{destdir},
295                                 genfeed("atom", $atomurl, $desc, $params{destpage}, @list));
296                         $toping{$params{destpage}}=1 unless $config{rebuild};
297                         $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/atom+xml" title="Atom" href="$atomurl" />};
298                 }
299         }
300         
301         return $ret;
302 } #}}}
304 sub pagetemplate_inline (@) { #{{{
305         my %params=@_;
306         my $page=$params{page};
307         my $template=$params{template};
309         $template->param(feedlinks => $feedlinks{$page})
310                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
311 } #}}}
313 sub get_inline_content ($$) { #{{{
314         my $page=shift;
315         my $destpage=shift;
316         
317         my $file=$pagesources{$page};
318         my $type=pagetype($file);
319         if (defined $type) {
320                 return htmlize($page, $type,
321                        linkify($page, $destpage,
322                        preprocess($page, $destpage,
323                        filter($page, $destpage,
324                        readfile(srcfile($file))))));
325         }
326         else {
327                 return "";
328         }
329 } #}}}
331 sub date_822 ($) { #{{{
332         my $time=shift;
334         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
335         POSIX::setlocale(&POSIX::LC_TIME, "C");
336         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
337         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
338         return $ret;
339 } #}}}
341 sub date_3339 ($) { #{{{
342         my $time=shift;
344         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
345         POSIX::setlocale(&POSIX::LC_TIME, "C");
346         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
347         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
348         return $ret;
349 } #}}}
351 sub absolute_urls ($$) { #{{{
352         # sucky sub because rss sucks
353         my $content=shift;
354         my $baseurl=shift;
356         my $url=$baseurl;
357         $url=~s/[^\/]+$//;
358         
359         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
360         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:\/\/)([^"]+)"/$1 href="$url$2"/mig;
361         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:\/\/)([^"]+)"/$1 src="$url$2"/mig;
362         return $content;
363 } #}}}
365 sub rsspage ($) { #{{{
366         return targetpage(shift, "rss");
367 } #}}}
369 sub atompage ($) { #{{{
370         return targetpage(shift, "atom");
371 } #}}}
373 sub genfeed ($$$$@) { #{{{
374         my $feedtype=shift;
375         my $feedurl=shift;
376         my $feeddesc=shift;
377         my $page=shift;
378         my @pages=@_;
379         
380         my $url=URI->new(encode_utf8($config{url}."/".urlto($page,"")));
381         
382         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
383         my $content="";
384         my $lasttime = 0;
385         foreach my $p (@pages) {
386                 my $u=URI->new(encode_utf8($config{url}."/".urlto($p, "")));
387                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
389                 $itemtemplate->param(
390                         title => pagetitle(basename($p)),
391                         url => $u,
392                         permalink => $u,
393                         cdate_822 => date_822($pagectime{$p}),
394                         mdate_822 => date_822($pagemtime{$p}),
395                         cdate_3339 => date_3339($pagectime{$p}),
396                         mdate_3339 => date_3339($pagemtime{$p}),
397                 );
399                 if ($itemtemplate->query(name => "enclosure")) {
400                         my $file=$pagesources{$p};
401                         my $type=pagetype($file);
402                         if (defined $type) {
403                                 $itemtemplate->param(content => $pcontent);
404                         }
405                         else {
406                                 my ($a, $b, $c, $d, $e, $f, $g, $size) = stat(srcfile($file));
407                                 my $mime="unknown";
408                                 eval q{use File::MimeInfo};
409                                 if (! $@) {
410                                         $mime = mimetype($file);
411                                 }
412                                 $itemtemplate->param(
413                                         enclosure => $u,
414                                         type => $mime,
415                                         length => $size,
416                                 );
417                         }
418                 }
419                 else {
420                         $itemtemplate->param(content => $pcontent);
421                 }
423                 run_hooks(pagetemplate => sub {
424                         shift->(page => $p, destpage => $page,
425                                 template => $itemtemplate);
426                 });
428                 $content.=$itemtemplate->output;
429                 $itemtemplate->clear_params;
431                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
432         }
434         my $template=template($feedtype."page.tmpl", blind_cache => 1);
435         $template->param(
436                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
437                 wikiname => $config{wikiname},
438                 pageurl => $url,
439                 content => $content,
440                 feeddesc => $feeddesc,
441                 feeddate => date_3339($lasttime),
442                 feedurl => $feedurl,
443                 version => $IkiWiki::version,
444         );
445         run_hooks(pagetemplate => sub {
446                 shift->(page => $page, destpage => $page,
447                         template => $template);
448         });
449         
450         return $template->output;
451 } #}}}
453 sub pingurl (@) { #{{{
454         return unless @{$config{pingurl}} && %toping;
456         eval q{require RPC::XML::Client};
457         if ($@) {
458                 debug(gettext("RPC::XML::Client not found, not pinging"));
459                 return;
460         }
462         # daemonize here so slow pings don't slow down wiki updates
463         defined(my $pid = fork) or error("Can't fork: $!");
464         return if $pid;
465         chdir '/';
466         setsid() or error("Can't start a new session: $!");
467         open STDIN, '/dev/null';
468         open STDOUT, '>/dev/null';
469         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
471         # Don't need to keep a lock on the wiki as a daemon.
472         IkiWiki::unlockwiki();
474         foreach my $page (keys %toping) {
475                 my $title=pagetitle(basename($page), 0);
476                 my $url="$config{url}/".urlto($page, "");
477                 foreach my $pingurl (@{$config{pingurl}}) {
478                         debug("Pinging $pingurl for $page");
479                         eval {
480                                 my $client = RPC::XML::Client->new($pingurl);
481                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
482                                         $title, $url);
483                                 my $res = $client->send_request($req);
484                                 if (! ref $res) {
485                                         debug("Did not receive response to ping");
486                                 }
487                                 my $r=$res->value;
488                                 if (! exists $r->{flerror} || $r->{flerror}) {
489                                         debug("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
490                                 }
491                         };
492                         if ($@) {
493                                 debug "Ping failed: $@";
494                         }
495                 }
496         }
498         exit 0; # daemon done
499 } #}}}