]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/inline.pm
really add
[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;
13 my @inline;
14 my $nested=0;
16 sub import { #{{{
17         hook(type => "getopt", id => "inline", call => \&getopt);
18         hook(type => "checkconfig", id => "inline", call => \&checkconfig);
19         hook(type => "sessioncgi", id => "inline", call => \&sessioncgi);
20         hook(type => "preprocess", id => "inline", 
21                 call => \&IkiWiki::preprocess_inline);
22         hook(type => "pagetemplate", id => "inline",
23                 call => \&IkiWiki::pagetemplate_inline);
24         hook(type => "format", id => "inline", call => \&format);
25         # Hook to change to do pinging since it's called late.
26         # This ensures each page only pings once and prevents slow
27         # pings interrupting page builds.
28         hook(type => "change", id => "inline", 
29                 call => \&IkiWiki::pingurl);
31 } # }}}
33 sub getopt () { #{{{
34         eval q{use Getopt::Long};
35         error($@) if $@;
36         Getopt::Long::Configure('pass_through');
37         GetOptions(
38                 "rss!" => \$config{rss},
39                 "atom!" => \$config{atom},
40                 "allowrss!" => \$config{allowrss},
41                 "allowatom!" => \$config{allowatom},
42         );
43 }
45 sub checkconfig () { #{{{
46         if (($config{rss} || $config{atom}) && ! length $config{url}) {
47                 error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
48         }
49         if ($config{rss}) {
50                 push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
51         }
52         if ($config{atom}) {
53                 push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
54         }
55 } #}}}
57 sub format (@) { #{{{
58         my %params=@_;
60         # Fill in the inline content generated earlier. This is actually an
61         # optimisation.
62         $params{content}=~s{<div class="inline" id="([^"]+)"></div>}{
63                 delete @inline[$1,]
64         }eg;
65         return $params{content};
66 } #}}}
68 sub sessioncgi () { #{{{
69         my $q=shift;
70         my $session=shift;
72         if ($q->param('do') eq 'blog') {
73                 my $page=IkiWiki::titlepage(decode_utf8($q->param('title')));
74                 $page=~s/(\/)/"__".ord($1)."__"/eg; # don't create subdirs
75                 # if the page already exists, munge it to be unique
76                 my $from=$q->param('from');
77                 my $add="";
78                 while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
79                         $add=1 unless length $add;
80                         $add++;
81                 }
82                 $q->param('page', $page.$add);
83                 # now go create the page
84                 $q->param('do', 'create');
85                 IkiWiki::cgi_editpage($q, $session);
86                 exit;
87         }
88 }
90 # Back to ikiwiki namespace for the rest, this code is very much
91 # internal to ikiwiki even though it's separated into a plugin.
92 package IkiWiki;
94 my %toping;
95 my %feedlinks;
97 sub preprocess_inline (@) { #{{{
98         my %params=@_;
99         
100         if (! exists $params{pages}) {
101                 error gettext("missing pages parameter");
102         }
103         my $raw=yesno($params{raw});
104         my $archive=yesno($params{archive});
105         my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
106         my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
107         my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
108         my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
109         my $feedonly=yesno($params{feedonly});
110         if (! exists $params{show} && ! $archive) {
111                 $params{show}=10;
112         }
113         if (! exists $params{feedshow} && exists $params{show}) {
114                 $params{feedshow}=$params{show};
115         }
116         my $desc;
117         if (exists $params{description}) {
118                 $desc = $params{description} 
119         }
120         else {
121                 $desc = $config{wikiname};
122         }
123         my $actions=yesno($params{actions});
124         if (exists $params{template}) {
125                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
126         }
127         else {
128                 $params{template} = $archive ? "archivepage" : "inlinepage";
129         }
131         my @list;
132         foreach my $page (keys %pagesources) {
133                 next if $page eq $params{page};
134                 if (pagespec_match($page, $params{pages}, location => $params{page})) {
135                         push @list, $page;
136                 }
137         }
139         if (exists $params{sort} && $params{sort} eq 'title') {
140                 @list=sort @list;
141         }
142         elsif (exists $params{sort} && $params{sort} eq 'mtime') {
143                 @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
144         }
145         elsif (! exists $params{sort} || $params{sort} eq 'age') {
146                 @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
147         }
148         else {
149                 return sprintf(gettext("unknown sort type %s"), $params{sort});
150         }
152         if (yesno($params{reverse})) {
153                 @list=reverse(@list);
154         }
156         if (exists $params{skip}) {
157                 @list=@list[$params{skip} .. scalar @list - 1];
158         }
159         
160         my @feedlist;
161         if ($feeds) {
162                 if (exists $params{feedshow} &&
163                     $params{feedshow} && @list > $params{feedshow}) {
164                         @feedlist=@list[0..$params{feedshow} - 1];
165                 }
166                 else {
167                         @feedlist=@list;
168                 }
169         }
170         
171         if ($params{show} && @list > $params{show}) {
172                 @list=@list[0..$params{show} - 1];
173         }
175         add_depends($params{page}, $params{pages});
176         # Explicitly add all currently displayed pages as dependencies, so
177         # that if they are removed or otherwise changed, the inline will be
178         # sure to be updated.
179         add_depends($params{page}, join(" or ", $#list >= $#feedlist ? @list : @feedlist));
181         my $feednum="";
183         my $feedid=join("\0", map { $_."\0".$params{$_} } sort keys %params);
184         if (exists $knownfeeds{$feedid}) {
185                 $feednum=$knownfeeds{$feedid};
186         }
187         else {
188                 if (exists $page_numfeeds{$params{destpage}}) {
189                         if ($feeds) {
190                                 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}};
191                         }
192                 }
193                 else {
194                         $feednum=$knownfeeds{$feedid}="";
195                         if ($feeds) {
196                                 $page_numfeeds{$params{destpage}}=1;
197                         }
198                 }
199         }
201         my $rssurl=basename(rsspage($params{destpage}).$feednum) if $feeds && $rss;
202         my $atomurl=basename(atompage($params{destpage}).$feednum) if $feeds && $atom;
203         my $ret="";
205         if ($config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
206                         (exists $params{postform} && yesno($params{postform})))) {
207                 # Add a blog post form, with feed buttons.
208                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
209                 $formtemplate->param(cgiurl => $config{cgiurl});
210                 $formtemplate->param(rootpage => 
211                         exists $params{rootpage} ? $params{rootpage} : $params{page});
212                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
213                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
214                 if (exists $params{postformtext}) {
215                         $formtemplate->param(postformtext =>
216                                 $params{postformtext});
217                 }
218                 else {
219                         $formtemplate->param(postformtext =>
220                                 gettext("Add a new post titled:"));
221                 }
222                 $ret.=$formtemplate->output;
223         }
224         elsif ($feeds && !$params{preview}) {
225                 # Add feed buttons.
226                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
227                 $linktemplate->param(rssurl => $rssurl) if $rss;
228                 $linktemplate->param(atomurl => $atomurl) if $atom;
229                 $ret.=$linktemplate->output;
230         }
231         
232         if (! $feedonly) {
233                 require HTML::Template;
234                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
235                 if (! @params) {
236                         return sprintf(gettext("nonexistant template %s"), $params{template});
237                 }
238                 my $template=HTML::Template->new(@params) unless $raw;
239         
240                 foreach my $page (@list) {
241                         my $file = $pagesources{$page};
242                         my $type = pagetype($file);
243                         if (! $raw || ($raw && ! defined $type)) {
244                                 unless ($archive && $quick) {
245                                         # Get the content before populating the
246                                         # template, since getting the content uses
247                                         # the same template if inlines are nested.
248                                         my $content=get_inline_content($page, $params{destpage});
249                                         $template->param(content => $content);
250                                 }
251                                 $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
252                                 $template->param(title => pagetitle(basename($page)));
253                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
254                                 $template->param(first => 1) if $page eq $list[0];
255                                 $template->param(last => 1) if $page eq $list[$#list];
256         
257                                 if ($actions) {
258                                         my $file = $pagesources{$page};
259                                         my $type = pagetype($file);
260                                         if ($config{discussion}) {
261                                                 my $discussionlink=gettext("discussion");
262                                                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
263                                                     (length $config{cgiurl} ||
264                                                      exists $links{$page."/".$discussionlink})) {
265                                                         $template->param(have_actions => 1);
266                                                         $template->param(discussionlink =>
267                                                                 htmllink($page,
268                                                                         $params{destpage},
269                                                                         gettext("Discussion"),
270                                                                         noimageinline => 1,
271                                                                         forcesubpage => 1));
272                                                 }
273                                         }
274                                         if (length $config{cgiurl} && defined $type) {
275                                                 $template->param(have_actions => 1);
276                                                 $template->param(editurl => cgiurl(do => "edit", page => $page));
277                                         }
278                                 }
279         
280                                 run_hooks(pagetemplate => sub {
281                                         shift->(page => $page, destpage => $params{destpage},
282                                                 template => $template,);
283                                 });
284         
285                                 $ret.=$template->output;
286                                 $template->clear_params;
287                         }
288                         else {
289                                 if (defined $type) {
290                                         $ret.="\n".
291                                               linkify($page, $params{destpage},
292                                               preprocess($page, $params{destpage},
293                                               filter($page, $params{destpage},
294                                               readfile(srcfile($file)))));
295                                 }
296                         }
297                 }
298         }
299         
300         if ($feeds) {
301                 if (exists $params{feedpages}) {
302                         @feedlist=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @feedlist;
303                 }
304         
305                 if ($rss) {
306                         my $rssp=rsspage($params{destpage}).$feednum;
307                         will_render($params{destpage}, $rssp);
308                         if (! $params{preview}) {
309                                 writefile($rssp, $config{destdir},
310                                         genfeed("rss",
311                                                 $config{url}."/".rsspage($params{destpage}).$feednum, $desc, $params{guid}, $params{destpage}, @feedlist));
312                                 $toping{$params{destpage}}=1 unless $config{rebuild};
313                                 $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/rss+xml" title="RSS" href="$rssurl" />};
314                         }
315                 }
316                 if ($atom) {
317                         my $atomp=atompage($params{destpage}).$feednum;
318                         will_render($params{destpage}, $atomp);
319                         if (! $params{preview}) {
320                                 writefile($atomp, $config{destdir},
321                                         genfeed("atom", $config{url}."/".atompage($params{destpage}).$feednum, $desc, $params{guid}, $params{destpage}, @feedlist));
322                                 $toping{$params{destpage}}=1 unless $config{rebuild};
323                                 $feedlinks{$params{destpage}}=qq{<link rel="alternate" type="application/atom+xml" title="Atom" href="$atomurl" />};
324                         }
325                 }
326         }
327         
328         return $ret if $raw || $nested;
329         push @inline, $ret;
330         return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
331 } #}}}
333 sub pagetemplate_inline (@) { #{{{
334         my %params=@_;
335         my $page=$params{page};
336         my $template=$params{template};
338         $template->param(feedlinks => $feedlinks{$page})
339                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
340 } #}}}
342 sub get_inline_content ($$) { #{{{
343         my $page=shift;
344         my $destpage=shift;
345         
346         my $file=$pagesources{$page};
347         my $type=pagetype($file);
348         if (defined $type) {
349                 $nested++;
350                 my $ret=htmlize($page, $destpage, $type,
351                        linkify($page, $destpage,
352                        preprocess($page, $destpage,
353                        filter($page, $destpage,
354                        readfile(srcfile($file))))));
355                 $nested--;
356                 return $ret;
357         }
358         else {
359                 return "";
360         }
361 } #}}}
363 sub date_822 ($) { #{{{
364         my $time=shift;
366         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
367         POSIX::setlocale(&POSIX::LC_TIME, "C");
368         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
369         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
370         return $ret;
371 } #}}}
373 sub date_3339 ($) { #{{{
374         my $time=shift;
376         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
377         POSIX::setlocale(&POSIX::LC_TIME, "C");
378         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
379         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
380         return $ret;
381 } #}}}
383 sub absolute_urls ($$) { #{{{
384         # sucky sub because rss sucks
385         my $content=shift;
386         my $baseurl=shift;
388         my $url=$baseurl;
389         $url=~s/[^\/]+$//;
391         # what is the non path part of the url?
392         my $top_uri = URI->new($url);
393         $top_uri->path_query(""); # reset the path
394         my $urltop = $top_uri->as_string;
396         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
397         # relative to another wiki page
398         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)([^\/][^"]*)"/$1 href="$url$2"/mig;
399         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)([^\/][^"]*)"/$1 src="$url$2"/mig;
400         # relative to the top of the site
401         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)(\/[^"]*)"/$1 href="$urltop$2"/mig;
402         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)(\/[^"]*)"/$1 src="$urltop$2"/mig;
403         return $content;
404 } #}}}
406 sub rsspage ($) { #{{{
407         return targetpage(shift, "rss");
408 } #}}}
410 sub atompage ($) { #{{{
411         return targetpage(shift, "atom");
412 } #}}}
414 sub genfeed ($$$$$@) { #{{{
415         my $feedtype=shift;
416         my $feedurl=shift;
417         my $feeddesc=shift;
418         my $guid=shift;
419         my $page=shift;
420         my @pages=@_;
421         
422         my $url=URI->new(encode_utf8($config{url}."/".urlto($page,"")));
423         
424         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
425         my $content="";
426         my $lasttime = 0;
427         foreach my $p (@pages) {
428                 my $u=URI->new(encode_utf8($config{url}."/".urlto($p, "")));
429                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
431                 $itemtemplate->param(
432                         title => pagetitle(basename($p)),
433                         url => $u,
434                         permalink => $u,
435                         cdate_822 => date_822($pagectime{$p}),
436                         mdate_822 => date_822($pagemtime{$p}),
437                         cdate_3339 => date_3339($pagectime{$p}),
438                         mdate_3339 => date_3339($pagemtime{$p}),
439                 );
441                 if (exists $pagestate{$p} &&
442                     exists $pagestate{$p}{meta}{guid}) {
443                         $itemtemplate->param(guid => $pagestate{$p}{meta}{guid});
444                 }
446                 if ($itemtemplate->query(name => "enclosure")) {
447                         my $file=$pagesources{$p};
448                         my $type=pagetype($file);
449                         if (defined $type) {
450                                 $itemtemplate->param(content => $pcontent);
451                         }
452                         else {
453                                 my $size=(srcfile_stat($file))[8];
454                                 my $mime="unknown";
455                                 eval q{use File::MimeInfo};
456                                 if (! $@) {
457                                         $mime = mimetype($file);
458                                 }
459                                 $itemtemplate->param(
460                                         enclosure => $u,
461                                         type => $mime,
462                                         length => $size,
463                                 );
464                         }
465                 }
466                 else {
467                         $itemtemplate->param(content => $pcontent);
468                 }
470                 run_hooks(pagetemplate => sub {
471                         shift->(page => $p, destpage => $page,
472                                 template => $itemtemplate);
473                 });
475                 $content.=$itemtemplate->output;
476                 $itemtemplate->clear_params;
478                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
479         }
481         my $template=template($feedtype."page.tmpl", blind_cache => 1);
482         $template->param(
483                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
484                 wikiname => $config{wikiname},
485                 pageurl => $url,
486                 content => $content,
487                 feeddesc => $feeddesc,
488                 guid => $guid,
489                 feeddate => date_3339($lasttime),
490                 feedurl => $feedurl,
491                 version => $IkiWiki::version,
492         );
493         run_hooks(pagetemplate => sub {
494                 shift->(page => $page, destpage => $page,
495                         template => $template);
496         });
497         
498         return $template->output;
499 } #}}}
501 sub pingurl (@) { #{{{
502         return unless @{$config{pingurl}} && %toping;
504         eval q{require RPC::XML::Client};
505         if ($@) {
506                 debug(gettext("RPC::XML::Client not found, not pinging"));
507                 return;
508         }
510         # daemonize here so slow pings don't slow down wiki updates
511         defined(my $pid = fork) or error("Can't fork: $!");
512         return if $pid;
513         chdir '/';
514         POSIX::setsid() or error("Can't start a new session: $!");
515         open STDIN, '/dev/null';
516         open STDOUT, '>/dev/null';
517         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
519         # Don't need to keep a lock on the wiki as a daemon.
520         IkiWiki::unlockwiki();
522         foreach my $page (keys %toping) {
523                 my $title=pagetitle(basename($page), 0);
524                 my $url="$config{url}/".urlto($page, "");
525                 foreach my $pingurl (@{$config{pingurl}}) {
526                         debug("Pinging $pingurl for $page");
527                         eval {
528                                 my $client = RPC::XML::Client->new($pingurl);
529                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
530                                         $title, $url);
531                                 my $res = $client->send_request($req);
532                                 if (! ref $res) {
533                                         debug("Did not receive response to ping");
534                                 }
535                                 my $r=$res->value;
536                                 if (! exists $r->{flerror} || $r->{flerror}) {
537                                         debug("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
538                                 }
539                         };
540                         if ($@) {
541                                 debug "Ping failed: $@";
542                         }
543                 }
544         }
546         exit 0; # daemon done
547 } #}}}