]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/inline.pm
some parameteraisation and generalisation
[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         $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         }
116
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         }
124
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         }
137
138         if (yesno($params{reverse})) {
139                 @list=reverse(@list);
140         }
141
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         }
149
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         # Force a scan of this page so any metadata that appears after this
156         # inline directive is available when inlining. The page normally 
157         # wouldn't be scanned if it's only being rebuilt because of a
158         # depedency.
159         IkiWiki::scan($pagesources{$params{page}});
160
161         my $feednum="";
162
163         my $feedid=join("\0", map { $_."\0".$params{$_} } sort keys %params);
164         if (exists $knownfeeds{$feedid}) {
165                 $feednum=$knownfeeds{$feedid};
166         }
167         else {
168                 if (exists $page_numfeeds{$params{destpage}}) {
169                         if ($feeds) {
170                                 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}};
171                         }
172                 }
173                 else {
174                         $feednum=$knownfeeds{$feedid}="";
175                         if ($feeds) {
176                                 $page_numfeeds{$params{destpage}}=1;
177                         }
178                 }
179         }
180
181         my $rssurl=basename(rsspage($params{destpage}).$feednum) if $feeds && $rss;
182         my $atomurl=basename(atompage($params{destpage}).$feednum) if $feeds && $atom;
183         my $ret="";
184
185         if ($config{cgiurl} && (exists $params{rootpage} ||
186                         (exists $params{postform} && yesno($params{postform})))) {
187                 # Add a blog post form, with feed buttons.
188                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
189                 $formtemplate->param(cgiurl => $config{cgiurl});
190                 $formtemplate->param(rootpage => 
191                         exists $params{rootpage} ? $params{rootpage} : $params{page});
192                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
193                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
194                 if (exists $params{postformtext}) {
195                         $formtemplate->param(postformtext =>
196                                 $params{postformtext});
197                 }
198                 else {
199                         $formtemplate->param(postformtext =>
200                                 gettext("Add a new post titled:"));
201                 }
202                 $ret.=$formtemplate->output;
203         }
204         elsif ($feeds) {
205                 # Add feed buttons.
206                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
207                 $linktemplate->param(rssurl => $rssurl) if $rss;
208                 $linktemplate->param(atomurl => $atomurl) if $atom;
209                 $ret.=$linktemplate->output;
210         }
211         
212         if (! $feedonly) {
213                 require HTML::Template;
214                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
215                 if (! @params) {
216                         return sprintf(gettext("nonexistant template %s"), $params{template});
217                 }
218                 my $template=HTML::Template->new(@params) unless $raw;
219         
220                 foreach my $page (@list) {
221                         my $file = $pagesources{$page};
222                         my $type = pagetype($file);
223                         if (! $raw || ($raw && ! defined $type)) {
224                                 unless ($archive && $quick) {
225                                         # Get the content before populating the
226                                         # template, since getting the content uses
227                                         # the same template if inlines are nested.
228                                         my $content=get_inline_content($page, $params{destpage});
229                                         $template->param(content => $content);
230                                 }
231                                 $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
232                                 $template->param(title => pagetitle(basename($page)));
233                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
234                                 $template->param(first => 1) if $page eq $list[0];
235                                 $template->param(last => 1) if $page eq $list[$#list];
236         
237                                 if ($actions) {
238                                         my $file = $pagesources{$page};
239                                         my $type = pagetype($file);
240                                         if ($config{discussion}) {
241                                                 my $discussionlink=gettext("discussion");
242                                                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
243                                                     (length $config{cgiurl} ||
244                                                      exists $links{$page."/".$discussionlink})) {
245                                                         $template->param(have_actions => 1);
246                                                         $template->param(discussionlink =>
247                                                                 htmllink($page,
248                                                                         $params{destpage},
249                                                                         gettext("Discussion"),
250                                                                         noimageinline => 1,
251                                                                         forcesubpage => 1));
252                                                 }
253                                         }
254                                         if (length $config{cgiurl} && defined $type) {
255                                                 $template->param(have_actions => 1);
256                                                 $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
257                                         }
258                                 }
259         
260                                 run_hooks(pagetemplate => sub {
261                                         shift->(page => $page, destpage => $params{destpage},
262                                                 template => $template,);
263                                 });
264         
265                                 $ret.=$template->output;
266                                 $template->clear_params;
267                         }
268                         else {
269                                 if (defined $type) {
270                                         $ret.="\n".
271                                               linkify($page, $params{destpage},
272                                               preprocess($page, $params{destpage},
273                                               filter($page, $params{destpage},
274                                               readfile(srcfile($file)))));
275                                 }
276                         }
277                 }
278         }
279         
280         if ($feeds) {
281                 if (exists $params{feedshow} && @list > $params{feedshow}) {
282                         @list=@list[0..$params{feedshow} - 1];
283                 }
284                 if (exists $params{feedpages}) {
285                         @list=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @list;
286                 }
287         
288                 if ($rss) {
289                         my $rssp=rsspage($params{destpage}).$feednum;
290                         will_render($params{destpage}, $rssp);
291                         writefile($rssp, $config{destdir},
292                                 genfeed("rss", $rssurl, $desc, $params{destpage}, @list));
293                         $toping{$params{destpage}}=1 unless $config{rebuild};
294                         $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/rss+xml" title="RSS" href="$rssurl" />};
295                 }
296                 if ($atom) {
297                         my $atomp=atompage($params{destpage}).$feednum;
298                         will_render($params{destpage}, $atomp);
299                         writefile($atomp, $config{destdir},
300                                 genfeed("atom", $atomurl, $desc, $params{destpage}, @list));
301                         $toping{$params{destpage}}=1 unless $config{rebuild};
302                         $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/atom+xml" title="Atom" href="$atomurl" />};
303                 }
304         }
305         
306         return $ret;
307 } #}}}
308
309 sub pagetemplate_inline (@) { #{{{
310         my %params=@_;
311         my $page=$params{page};
312         my $template=$params{template};
313
314         $template->param(feedlinks => $feedlinks{$page})
315                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
316 } #}}}
317
318 sub get_inline_content ($$) { #{{{
319         my $page=shift;
320         my $destpage=shift;
321         
322         my $file=$pagesources{$page};
323         my $type=pagetype($file);
324         if (defined $type) {
325                 return htmlize($page, $type,
326                        linkify($page, $destpage,
327                        preprocess($page, $destpage,
328                        filter($page, $destpage,
329                        readfile(srcfile($file))))));
330         }
331         else {
332                 return "";
333         }
334 } #}}}
335
336 sub date_822 ($) { #{{{
337         my $time=shift;
338
339         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
340         POSIX::setlocale(&POSIX::LC_TIME, "C");
341         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
342         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
343         return $ret;
344 } #}}}
345
346 sub date_3339 ($) { #{{{
347         my $time=shift;
348
349         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
350         POSIX::setlocale(&POSIX::LC_TIME, "C");
351         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
352         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
353         return $ret;
354 } #}}}
355
356 sub absolute_urls ($$) { #{{{
357         # sucky sub because rss sucks
358         my $content=shift;
359         my $baseurl=shift;
360
361         my $url=$baseurl;
362         $url=~s/[^\/]+$//;
363         
364         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
365         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:\/\/)([^"]+)"/$1 href="$url$2"/mig;
366         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:\/\/)([^"]+)"/$1 src="$url$2"/mig;
367         return $content;
368 } #}}}
369
370 sub rsspage ($) { #{{{
371         return targetpage(shift, "rss");
372 } #}}}
373
374 sub atompage ($) { #{{{
375         return targetpage(shift, "atom");
376 } #}}}
377
378 sub genfeed ($$$$@) { #{{{
379         my $feedtype=shift;
380         my $feedurl=shift;
381         my $feeddesc=shift;
382         my $page=shift;
383         my @pages=@_;
384         
385         my $url=URI->new(encode_utf8($config{url}."/".urlto($page,"")));
386         
387         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
388         my $content="";
389         my $lasttime = 0;
390         foreach my $p (@pages) {
391                 my $u=URI->new(encode_utf8($config{url}."/".urlto($p, "")));
392                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
393
394                 $itemtemplate->param(
395                         title => pagetitle(basename($p)),
396                         url => $u,
397                         permalink => $u,
398                         cdate_822 => date_822($pagectime{$p}),
399                         mdate_822 => date_822($pagemtime{$p}),
400                         cdate_3339 => date_3339($pagectime{$p}),
401                         mdate_3339 => date_3339($pagemtime{$p}),
402                 );
403
404                 if ($itemtemplate->query(name => "enclosure")) {
405                         my $file=$pagesources{$p};
406                         my $type=pagetype($file);
407                         if (defined $type) {
408                                 $itemtemplate->param(content => $pcontent);
409                         }
410                         else {
411                                 my ($a, $b, $c, $d, $e, $f, $g, $size) = stat(srcfile($file));
412                                 my $mime="unknown";
413                                 eval q{use File::MimeInfo};
414                                 if (! $@) {
415                                         $mime = mimetype($file);
416                                 }
417                                 $itemtemplate->param(
418                                         enclosure => $u,
419                                         type => $mime,
420                                         length => $size,
421                                 );
422                         }
423                 }
424                 else {
425                         $itemtemplate->param(content => $pcontent);
426                 }
427
428                 run_hooks(pagetemplate => sub {
429                         shift->(page => $p, destpage => $page,
430                                 template => $itemtemplate);
431                 });
432
433                 $content.=$itemtemplate->output;
434                 $itemtemplate->clear_params;
435
436                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
437         }
438
439         my $template=template($feedtype."page.tmpl", blind_cache => 1);
440         $template->param(
441                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
442                 wikiname => $config{wikiname},
443                 pageurl => $url,
444                 content => $content,
445                 feeddesc => $feeddesc,
446                 feeddate => date_3339($lasttime),
447                 feedurl => $feedurl,
448                 version => $IkiWiki::version,
449         );
450         run_hooks(pagetemplate => sub {
451                 shift->(page => $page, destpage => $page,
452                         template => $template);
453         });
454         
455         return $template->output;
456 } #}}}
457
458 sub pingurl (@) { #{{{
459         return unless @{$config{pingurl}} && %toping;
460
461         eval q{require RPC::XML::Client};
462         if ($@) {
463                 debug(gettext("RPC::XML::Client not found, not pinging"));
464                 return;
465         }
466
467         # daemonize here so slow pings don't slow down wiki updates
468         defined(my $pid = fork) or error("Can't fork: $!");
469         return if $pid;
470         chdir '/';
471         setsid() or error("Can't start a new session: $!");
472         open STDIN, '/dev/null';
473         open STDOUT, '>/dev/null';
474         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
475
476         # Don't need to keep a lock on the wiki as a daemon.
477         IkiWiki::unlockwiki();
478
479         foreach my $page (keys %toping) {
480                 my $title=pagetitle(basename($page), 0);
481                 my $url="$config{url}/".urlto($page, "");
482                 foreach my $pingurl (@{$config{pingurl}}) {
483                         debug("Pinging $pingurl for $page");
484                         eval {
485                                 my $client = RPC::XML::Client->new($pingurl);
486                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
487                                         $title, $url);
488                                 my $res = $client->send_request($req);
489                                 if (! ref $res) {
490                                         debug("Did not receive response to ping");
491                                 }
492                                 my $r=$res->value;
493                                 if (! exists $r->{flerror} || $r->{flerror}) {
494                                         debug("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
495                                 }
496                         };
497                         if ($@) {
498                                 debug "Ping failed: $@";
499                         }
500                 }
501         }
502
503         exit 0; # daemon done
504 } #}}}
505
506 1