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