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