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