02c04cc003e4886414b48afc8e2e60b87f385c9a
[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 my @inline;
14 my $nested=0;
15
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);
30
31 } # }}}
32
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 }
44
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 } #}}}
56
57 sub format (@) { #{{{
58         my %params=@_;
59
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 } #}}}
67
68 sub sessioncgi () { #{{{
69         my $q=shift;
70         my $session=shift;
71
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 }
89
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;
93
94 my %toping;
95 my %feedlinks;
96
97 sub preprocess_inline (@) { #{{{
98         my %params=@_;
99         
100         if (! exists $params{pages}) {
101                 return "[[inline ".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         }
130
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         }
138
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         }
151
152         if (yesno($params{reverse})) {
153                 @list=reverse(@list);
154         }
155
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         }
174
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));
180
181         my $feednum="";
182
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         }
200
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="";
204
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{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{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 } #}}}
332
333 sub pagetemplate_inline (@) { #{{{
334         my %params=@_;
335         my $page=$params{page};
336         my $template=$params{template};
337
338         $template->param(feedlinks => $feedlinks{$page})
339                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
340 } #}}}
341
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 } #}}}
362
363 sub date_822 ($) { #{{{
364         my $time=shift;
365
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 } #}}}
372
373 sub date_3339 ($) { #{{{
374         my $time=shift;
375
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 } #}}}
382
383 sub absolute_urls ($$) { #{{{
384         # sucky sub because rss sucks
385         my $content=shift;
386         my $baseurl=shift;
387
388         my $url=$baseurl;
389         $url=~s/[^\/]+$//;
390
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;
395
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 } #}}}
405
406 sub rsspage ($) { #{{{
407         return targetpage(shift, "rss");
408 } #}}}
409
410 sub atompage ($) { #{{{
411         return targetpage(shift, "atom");
412 } #}}}
413
414 sub genfeed ($$$$@) { #{{{
415         my $feedtype=shift;
416         my $feedurl=shift;
417         my $feeddesc=shift;
418         my $page=shift;
419         my @pages=@_;
420         
421         my $url=URI->new(encode_utf8($config{url}."/".urlto($page,"")));
422         
423         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
424         my $content="";
425         my $lasttime = 0;
426         foreach my $p (@pages) {
427                 my $u=URI->new(encode_utf8($config{url}."/".urlto($p, "")));
428                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
429
430                 $itemtemplate->param(
431                         title => pagetitle(basename($p)),
432                         url => $u,
433                         permalink => $u,
434                         cdate_822 => date_822($pagectime{$p}),
435                         mdate_822 => date_822($pagemtime{$p}),
436                         cdate_3339 => date_3339($pagectime{$p}),
437                         mdate_3339 => date_3339($pagemtime{$p}),
438                 );
439
440                 if (exists $pagestate{$p} &&
441                     exists $pagestate{$p}{meta}{guid}) {
442                         $itemtemplate->param(guid => $pagestate{$p}{meta}{guid});
443                 }
444
445                 if ($itemtemplate->query(name => "enclosure")) {
446                         my $file=$pagesources{$p};
447                         my $type=pagetype($file);
448                         if (defined $type) {
449                                 $itemtemplate->param(content => $pcontent);
450                         }
451                         else {
452                                 my $size=(srcfile_stat($file))[8];
453                                 my $mime="unknown";
454                                 eval q{use File::MimeInfo};
455                                 if (! $@) {
456                                         $mime = mimetype($file);
457                                 }
458                                 $itemtemplate->param(
459                                         enclosure => $u,
460                                         type => $mime,
461                                         length => $size,
462                                 );
463                         }
464                 }
465                 else {
466                         $itemtemplate->param(content => $pcontent);
467                 }
468
469                 run_hooks(pagetemplate => sub {
470                         shift->(page => $p, destpage => $page,
471                                 template => $itemtemplate);
472                 });
473
474                 $content.=$itemtemplate->output;
475                 $itemtemplate->clear_params;
476
477                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
478         }
479
480         my $template=template($feedtype."page.tmpl", blind_cache => 1);
481         $template->param(
482                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
483                 wikiname => $config{wikiname},
484                 pageurl => $url,
485                 content => $content,
486                 feeddesc => $feeddesc,
487                 feeddate => date_3339($lasttime),
488                 feedurl => $feedurl,
489                 version => $IkiWiki::version,
490         );
491         run_hooks(pagetemplate => sub {
492                 shift->(page => $page, destpage => $page,
493                         template => $template);
494         });
495         
496         return $template->output;
497 } #}}}
498
499 sub pingurl (@) { #{{{
500         return unless @{$config{pingurl}} && %toping;
501
502         eval q{require RPC::XML::Client};
503         if ($@) {
504                 debug(gettext("RPC::XML::Client not found, not pinging"));
505                 return;
506         }
507
508         # daemonize here so slow pings don't slow down wiki updates
509         defined(my $pid = fork) or error("Can't fork: $!");
510         return if $pid;
511         chdir '/';
512         POSIX::setsid() or error("Can't start a new session: $!");
513         open STDIN, '/dev/null';
514         open STDOUT, '>/dev/null';
515         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
516
517         # Don't need to keep a lock on the wiki as a daemon.
518         IkiWiki::unlockwiki();
519
520         foreach my $page (keys %toping) {
521                 my $title=pagetitle(basename($page), 0);
522                 my $url="$config{url}/".urlto($page, "");
523                 foreach my $pingurl (@{$config{pingurl}}) {
524                         debug("Pinging $pingurl for $page");
525                         eval {
526                                 my $client = RPC::XML::Client->new($pingurl);
527                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
528                                         $title, $url);
529                                 my $res = $client->send_request($req);
530                                 if (! ref $res) {
531                                         debug("Did not receive response to ping");
532                                 }
533                                 my $r=$res->value;
534                                 if (! exists $r->{flerror} || $r->{flerror}) {
535                                         debug("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
536                                 }
537                         };
538                         if ($@) {
539                                 debug "Ping failed: $@";
540                         }
541                 }
542         }
543
544         exit 0; # daemon done
545 } #}}}
546
547 1