]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/inline.pm
web commit by bremner: a bit rough, but hopefully someone finds it useful
[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                 "allowrss!" => \$config{allowrss},
38                 "allowatom!" => \$config{allowatom},
39         );
40 }
41
42 sub checkconfig () { #{{{
43         if (($config{rss} || $config{atom}) && ! length $config{url}) {
44                 error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
45         }
46         if ($config{rss}) {
47                 push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
48         }
49         if ($config{atom}) {
50                 push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
51         }
52 } #}}}
53
54 sub sessioncgi () { #{{{
55         my $q=shift;
56         my $session=shift;
57
58         if ($q->param('do') eq 'blog') {
59                 my $page=decode_utf8($q->param('title'));
60                 $page=~s/\///g; # no slashes in blog posts
61                 # if the page already exists, munge it to be unique
62                 my $from=$q->param('from');
63                 my $add="";
64                 while (exists $IkiWiki::pagecase{lc($from."/".IkiWiki::titlepage($page).$add)}) {
65                         $add=1 unless length $add;
66                         $add++;
67                 }
68                 $q->param('page', $page.$add);
69                 # now go create the page
70                 $q->param('do', 'create');
71                 IkiWiki::cgi_editpage($q, $session);
72                 exit;
73         }
74 }
75
76 # Back to ikiwiki namespace for the rest, this code is very much
77 # internal to ikiwiki even though it's separated into a plugin.
78 package IkiWiki;
79
80 my %toping;
81 my %feedlinks;
82
83 sub yesno ($) { #{{{
84         my $val=shift;
85         return (defined $val && lc($val) eq "yes");
86 } #}}}
87
88 sub preprocess_inline (@) { #{{{
89         my %params=@_;
90         
91         if (! exists $params{pages}) {
92                 return "";
93         }
94         my $raw=yesno($params{raw});
95         my $archive=yesno($params{archive});
96         my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
97         my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
98         my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
99         my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
100         my $feedonly=yesno($params{feedonly});
101         if (! exists $params{show} && ! $archive) {
102                 $params{show}=10;
103         }
104         my $desc;
105         if (exists $params{description}) {
106                 $desc = $params{description} 
107         } else {
108                 $desc = $config{wikiname};
109         }
110         my $actions=yesno($params{actions});
111         if (exists $params{template}) {
112                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
113         }
114         else {
115                 $params{template} = $archive ? "archivepage" : "inlinepage";
116         }
117
118         my @list;
119         foreach my $page (keys %pagesources) {
120                 next if $page eq $params{page};
121                 if (pagespec_match($page, $params{pages}, location => $params{page})) {
122                         push @list, $page;
123                 }
124         }
125
126         if (exists $params{sort} && $params{sort} eq 'title') {
127                 @list=sort @list;
128         }
129         elsif (exists $params{sort} && $params{sort} eq 'mtime') {
130                 @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
131         }
132         elsif (! exists $params{sort} || $params{sort} eq 'age') {
133                 @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
134         }
135         else {
136                 return sprintf(gettext("unknown sort type %s"), $params{sort});
137         }
138
139         if (yesno($params{reverse})) {
140                 @list=reverse(@list);
141         }
142
143         if (exists $params{skip}) {
144                 @list=@list[$params{skip} .. scalar @list - 1];
145         }
146         
147         if ($params{show} && @list > $params{show}) {
148                 @list=@list[0..$params{show} - 1];
149         }
150
151         add_depends($params{page}, $params{pages});
152         # Explicitly add all currently displayed pages as dependencies, so
153         # that if they are removed or otherwise changed, the inline will be
154         # sure to be updated.
155         add_depends($params{page}, join(" or ", @list));
156
157         my $feednum="";
158
159         my $feedid=join("\0", map { $_."\0".$params{$_} } sort keys %params);
160         if (exists $knownfeeds{$feedid}) {
161                 $feednum=$knownfeeds{$feedid};
162         }
163         else {
164                 if (exists $page_numfeeds{$params{destpage}}) {
165                         if ($feeds) {
166                                 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}};
167                         }
168                 }
169                 else {
170                         $feednum=$knownfeeds{$feedid}="";
171                         if ($feeds) {
172                                 $page_numfeeds{$params{destpage}}=1;
173                         }
174                 }
175         }
176
177         my $rssurl=basename(rsspage($params{destpage}).$feednum) if $feeds && $rss;
178         my $atomurl=basename(atompage($params{destpage}).$feednum) if $feeds && $atom;
179         my $ret="";
180
181         if ($config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
182                         (exists $params{postform} && yesno($params{postform})))) {
183                 # Add a blog post form, with feed buttons.
184                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
185                 $formtemplate->param(cgiurl => $config{cgiurl});
186                 $formtemplate->param(rootpage => 
187                         exists $params{rootpage} ? $params{rootpage} : $params{page});
188                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
189                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
190                 if (exists $params{postformtext}) {
191                         $formtemplate->param(postformtext =>
192                                 $params{postformtext});
193                 }
194                 else {
195                         $formtemplate->param(postformtext =>
196                                 gettext("Add a new post titled:"));
197                 }
198                 $ret.=$formtemplate->output;
199         }
200         elsif ($feeds && !$params{preview}) {
201                 # Add feed buttons.
202                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
203                 $linktemplate->param(rssurl => $rssurl) if $rss;
204                 $linktemplate->param(atomurl => $atomurl) if $atom;
205                 $ret.=$linktemplate->output;
206         }
207         
208         if (! $feedonly) {
209                 require HTML::Template;
210                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
211                 if (! @params) {
212                         return sprintf(gettext("nonexistant template %s"), $params{template});
213                 }
214                 my $template=HTML::Template->new(@params) unless $raw;
215         
216                 foreach my $page (@list) {
217                         my $file = $pagesources{$page};
218                         my $type = pagetype($file);
219                         if (! $raw || ($raw && ! defined $type)) {
220                                 unless ($archive && $quick) {
221                                         # Get the content before populating the
222                                         # template, since getting the content uses
223                                         # the same template if inlines are nested.
224                                         my $content=get_inline_content($page, $params{destpage});
225                                         $template->param(content => $content);
226                                 }
227                                 $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
228                                 $template->param(title => pagetitle(basename($page)));
229                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
230                                 $template->param(first => 1) if $page eq $list[0];
231                                 $template->param(last => 1) if $page eq $list[$#list];
232         
233                                 if ($actions) {
234                                         my $file = $pagesources{$page};
235                                         my $type = pagetype($file);
236                                         if ($config{discussion}) {
237                                                 my $discussionlink=gettext("discussion");
238                                                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
239                                                     (length $config{cgiurl} ||
240                                                      exists $links{$page."/".$discussionlink})) {
241                                                         $template->param(have_actions => 1);
242                                                         $template->param(discussionlink =>
243                                                                 htmllink($page,
244                                                                         $params{destpage},
245                                                                         gettext("Discussion"),
246                                                                         noimageinline => 1,
247                                                                         forcesubpage => 1));
248                                                 }
249                                         }
250                                         if (length $config{cgiurl} && defined $type) {
251                                                 $template->param(have_actions => 1);
252                                                 $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
253                                         }
254                                 }
255         
256                                 run_hooks(pagetemplate => sub {
257                                         shift->(page => $page, destpage => $params{destpage},
258                                                 template => $template,);
259                                 });
260         
261                                 $ret.=$template->output;
262                                 $template->clear_params;
263                         }
264                         else {
265                                 if (defined $type) {
266                                         $ret.="\n".
267                                               linkify($page, $params{destpage},
268                                               preprocess($page, $params{destpage},
269                                               filter($page, $params{destpage},
270                                               readfile(srcfile($file)))));
271                                 }
272                         }
273                 }
274         }
275         
276         if ($feeds) {
277                 if (exists $params{feedshow} && @list > $params{feedshow}) {
278                         @list=@list[0..$params{feedshow} - 1];
279                 }
280                 if (exists $params{feedpages}) {
281                         @list=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @list;
282                 }
283         
284                 if ($rss) {
285                         my $rssp=rsspage($params{destpage}).$feednum;
286                         will_render($params{destpage}, $rssp);
287                         if (! $params{preview}) {
288                                 writefile($rssp, $config{destdir},
289                                         genfeed("rss", $rssurl, $desc, $params{destpage}, @list));
290                                 $toping{$params{destpage}}=1 unless $config{rebuild};
291                                 $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/rss+xml" title="RSS" href="$rssurl" />};
292                         }
293                 }
294                 if ($atom) {
295                         my $atomp=atompage($params{destpage}).$feednum;
296                         will_render($params{destpage}, $atomp);
297                         if (! $params{preview}) {
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         
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