]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/inline.pm
looking closer, the existing %knownfeeds won't work
[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 => "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=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                 # make sure the editpage plugin in loaded
135                 if (IkiWiki->can("cgi_editpage")) {
136                         IkiWiki::cgi_editpage($q, $session);
137                 }
138                 else {
139                         error(gettext("page editing not allowed"));
140                 }
141                 exit;
142         }
143 }
144
145 # Back to ikiwiki namespace for the rest, this code is very much
146 # internal to ikiwiki even though it's separated into a plugin.
147 package IkiWiki;
148
149 my %toping;
150 my %feedlinks;
151
152 sub preprocess_inline (@) { #{{{
153         my %params=@_;
154         
155         if (! exists $params{pages}) {
156                 error gettext("missing pages parameter");
157         }
158         my $raw=yesno($params{raw});
159         my $archive=yesno($params{archive});
160         my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
161         my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
162         my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
163         my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
164         my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
165         my $feedonly=yesno($params{feedonly});
166         if (! exists $params{show} && ! $archive) {
167                 $params{show}=10;
168         }
169         if (! exists $params{feedshow} && exists $params{show}) {
170                 $params{feedshow}=$params{show};
171         }
172         my $desc;
173         if (exists $params{description}) {
174                 $desc = $params{description} 
175         }
176         else {
177                 $desc = $config{wikiname};
178         }
179         my $actions=yesno($params{actions});
180         if (exists $params{template}) {
181                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
182         }
183         else {
184                 $params{template} = $archive ? "archivepage" : "inlinepage";
185         }
186
187         my @list;
188         foreach my $page (keys %pagesources) {
189                 next if $page eq $params{page};
190                 if (pagespec_match($page, $params{pages}, location => $params{page})) {
191                         push @list, $page;
192                 }
193         }
194
195         if (exists $params{sort} && $params{sort} eq 'title') {
196                 @list=sort { pagetitle(basename($a)) cmp pagetitle(basename($b)) } @list;
197         }
198         elsif (exists $params{sort} && $params{sort} eq 'mtime') {
199                 @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
200         }
201         elsif (! exists $params{sort} || $params{sort} eq 'age') {
202                 @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
203         }
204         else {
205                 error sprintf(gettext("unknown sort type %s"), $params{sort});
206         }
207
208         if (yesno($params{reverse})) {
209                 @list=reverse(@list);
210         }
211
212         if (exists $params{skip}) {
213                 @list=@list[$params{skip} .. scalar @list - 1];
214         }
215         
216         my @feedlist;
217         if ($feeds) {
218                 if (exists $params{feedshow} &&
219                     $params{feedshow} && @list > $params{feedshow}) {
220                         @feedlist=@list[0..$params{feedshow} - 1];
221                 }
222                 else {
223                         @feedlist=@list;
224                 }
225         }
226         
227         if ($params{show} && @list > $params{show}) {
228                 @list=@list[0..$params{show} - 1];
229         }
230
231         add_depends($params{page}, $params{pages});
232         # Explicitly add all currently displayed pages as dependencies, so
233         # that if they are removed or otherwise changed, the inline will be
234         # sure to be updated.
235         add_depends($params{page}, join(" or ", $#list >= $#feedlist ? @list : @feedlist));
236         
237         if ($feeds && exists $params{feedpages}) {
238                 @feedlist=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @feedlist;
239         }
240
241         my $feednum="";
242
243         my $feedid=join("\0", map { $_."\0".$params{$_} } sort keys %params);
244         if (exists $knownfeeds{$feedid}) {
245                 $feednum=$knownfeeds{$feedid};
246         }
247         else {
248                 if (exists $page_numfeeds{$params{destpage}}) {
249                         if ($feeds) {
250                                 $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}};
251                         }
252                 }
253                 else {
254                         $feednum=$knownfeeds{$feedid}="";
255                         if ($feeds) {
256                                 $page_numfeeds{$params{destpage}}=1;
257                         }
258                 }
259         }
260
261         my $rssurl=basename(rsspage($params{destpage}).$feednum) if $feeds && $rss;
262         my $atomurl=basename(atompage($params{destpage}).$feednum) if $feeds && $atom;
263         my $ret="";
264
265         if (length $config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
266             (exists $params{postform} && yesno($params{postform}))) &&
267             IkiWiki->can("cgi_editpage")) {
268                 # Add a blog post form, with feed buttons.
269                 my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
270                 $formtemplate->param(cgiurl => $config{cgiurl});
271                 my $rootpage;
272                 if (exists $params{rootpage}) {
273                         $rootpage=bestlink($params{page}, $params{rootpage});
274                         if (!length $rootpage) {
275                                 $rootpage=$params{rootpage};
276                         }
277                 }
278                 else {
279                         $rootpage=$params{page};
280                 }
281                 $formtemplate->param(rootpage => $rootpage);
282                 $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
283                 $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
284                 if (exists $params{postformtext}) {
285                         $formtemplate->param(postformtext =>
286                                 $params{postformtext});
287                 }
288                 else {
289                         $formtemplate->param(postformtext =>
290                                 gettext("Add a new post titled:"));
291                 }
292                 $ret.=$formtemplate->output;
293                 
294                 # The post form includes the feed buttons, so
295                 # emptyfeeds cannot be hidden.
296                 $emptyfeeds=1;
297         }
298         elsif ($feeds && !$params{preview} &&
299                ! (! $emptyfeeds && ! @feedlist)) {
300                 # Add feed buttons.
301                 my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
302                 $linktemplate->param(rssurl => $rssurl) if $rss;
303                 $linktemplate->param(atomurl => $atomurl) if $atom;
304                 $ret.=$linktemplate->output;
305         }
306         
307         if (! $feedonly) {
308                 require HTML::Template;
309                 my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
310                 if (! @params) {
311                         error sprintf(gettext("nonexistant template %s"), $params{template});
312                 }
313                 my $template=HTML::Template->new(@params) unless $raw;
314         
315                 foreach my $page (@list) {
316                         my $file = $pagesources{$page};
317                         my $type = pagetype($file);
318                         if (! $raw || ($raw && ! defined $type)) {
319                                 unless ($archive && $quick) {
320                                         # Get the content before populating the
321                                         # template, since getting the content uses
322                                         # the same template if inlines are nested.
323                                         my $content=get_inline_content($page, $params{destpage});
324                                         $template->param(content => $content);
325                                 }
326                                 $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
327                                 $template->param(title => pagetitle(basename($page)));
328                                 $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
329                                 $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
330                                 $template->param(first => 1) if $page eq $list[0];
331                                 $template->param(last => 1) if $page eq $list[$#list];
332         
333                                 if ($actions) {
334                                         my $file = $pagesources{$page};
335                                         my $type = pagetype($file);
336                                         if ($config{discussion}) {
337                                                 my $discussionlink=gettext("discussion");
338                                                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
339                                                     (length $config{cgiurl} ||
340                                                      exists $links{$page."/".$discussionlink})) {
341                                                         $template->param(have_actions => 1);
342                                                         $template->param(discussionlink =>
343                                                                 htmllink($page,
344                                                                         $params{destpage},
345                                                                         gettext("Discussion"),
346                                                                         noimageinline => 1,
347                                                                         forcesubpage => 1));
348                                                 }
349                                         }
350                                         if (length $config{cgiurl} && defined $type) {
351                                                 $template->param(have_actions => 1);
352                                                 $template->param(editurl => cgiurl(do => "edit", page => $page));
353                                         }
354                                 }
355         
356                                 run_hooks(pagetemplate => sub {
357                                         shift->(page => $page, destpage => $params{destpage},
358                                                 template => $template,);
359                                 });
360         
361                                 $ret.=$template->output;
362                                 $template->clear_params;
363                         }
364                         else {
365                                 if (defined $type) {
366                                         $ret.="\n".
367                                               linkify($page, $params{destpage},
368                                               preprocess($page, $params{destpage},
369                                               filter($page, $params{destpage},
370                                               readfile(srcfile($file)))));
371                                 }
372                         }
373                 }
374         }
375         
376         if ($feeds && ! (! $emptyfeeds && ! @feedlist)) {
377                 if ($rss) {
378                         my $rssp=rsspage($params{destpage}).$feednum;
379                         will_render($params{destpage}, $rssp);
380                         if (! $params{preview}) {
381                                 writefile($rssp, $config{destdir},
382                                         genfeed("rss",
383                                                 $config{url}."/".$rssp, $desc, $params{guid}, $params{destpage}, @feedlist));
384                                 $toping{$params{destpage}}=1 unless $config{rebuild};
385                                 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$desc (RSS)" href="$rssurl" />};
386                         }
387                 }
388                 if ($atom) {
389                         my $atomp=atompage($params{destpage}).$feednum;
390                         will_render($params{destpage}, $atomp);
391                         if (! $params{preview}) {
392                                 writefile($atomp, $config{destdir},
393                                         genfeed("atom", $config{url}."/".$atomp, $desc, $params{guid}, $params{destpage}, @feedlist));
394                                 $toping{$params{destpage}}=1 unless $config{rebuild};
395                                 $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$desc (Atom)" href="$atomurl" />};
396                         }
397                 }
398         }
399         
400         return $ret if $raw || $nested;
401         push @inline, $ret;
402         return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
403 } #}}}
404
405 sub pagetemplate_inline (@) { #{{{
406         my %params=@_;
407         my $page=$params{page};
408         my $template=$params{template};
409
410         $template->param(feedlinks => $feedlinks{$page})
411                 if exists $feedlinks{$page} && $template->query(name => "feedlinks");
412 } #}}}
413
414 sub get_inline_content ($$) { #{{{
415         my $page=shift;
416         my $destpage=shift;
417         
418         my $file=$pagesources{$page};
419         my $type=pagetype($file);
420         if (defined $type) {
421                 $nested++;
422                 my $ret=htmlize($page, $destpage, $type,
423                        linkify($page, $destpage,
424                        preprocess($page, $destpage,
425                        filter($page, $destpage,
426                        readfile(srcfile($file))))));
427                 $nested--;
428                 return $ret;
429         }
430         else {
431                 return "";
432         }
433 } #}}}
434
435 sub date_822 ($) { #{{{
436         my $time=shift;
437
438         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
439         POSIX::setlocale(&POSIX::LC_TIME, "C");
440         my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
441         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
442         return $ret;
443 } #}}}
444
445 sub date_3339 ($) { #{{{
446         my $time=shift;
447
448         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
449         POSIX::setlocale(&POSIX::LC_TIME, "C");
450         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
451         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
452         return $ret;
453 } #}}}
454
455 sub absolute_urls ($$) { #{{{
456         # sucky sub because rss sucks
457         my $content=shift;
458         my $baseurl=shift;
459
460         my $url=$baseurl;
461         $url=~s/[^\/]+$//;
462
463         # what is the non path part of the url?
464         my $top_uri = URI->new($url);
465         $top_uri->path_query(""); # reset the path
466         my $urltop = $top_uri->as_string;
467
468         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
469         # relative to another wiki page
470         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)([^\/][^"]*)"/$1 href="$url$2"/mig;
471         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)([^\/][^"]*)"/$1 src="$url$2"/mig;
472         # relative to the top of the site
473         $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)(\/[^"]*)"/$1 href="$urltop$2"/mig;
474         $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)(\/[^"]*)"/$1 src="$urltop$2"/mig;
475         return $content;
476 } #}}}
477
478 sub rsspage ($) { #{{{
479         return targetpage(shift, "rss");
480 } #}}}
481
482 sub atompage ($) { #{{{
483         return targetpage(shift, "atom");
484 } #}}}
485
486 sub genfeed ($$$$$@) { #{{{
487         my $feedtype=shift;
488         my $feedurl=shift;
489         my $feeddesc=shift;
490         my $guid=shift;
491         my $page=shift;
492         my @pages=@_;
493         
494         my $url=URI->new(encode_utf8(urlto($page,"",1)));
495         
496         my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
497         my $content="";
498         my $lasttime = 0;
499         foreach my $p (@pages) {
500                 my $u=URI->new(encode_utf8(urlto($p, "", 1)));
501                 my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
502
503                 $itemtemplate->param(
504                         title => pagetitle(basename($p)),
505                         url => $u,
506                         permalink => $u,
507                         cdate_822 => date_822($pagectime{$p}),
508                         mdate_822 => date_822($pagemtime{$p}),
509                         cdate_3339 => date_3339($pagectime{$p}),
510                         mdate_3339 => date_3339($pagemtime{$p}),
511                 );
512
513                 if (exists $pagestate{$p} &&
514                     exists $pagestate{$p}{meta}{guid}) {
515                         $itemtemplate->param(guid => $pagestate{$p}{meta}{guid});
516                 }
517
518                 if ($itemtemplate->query(name => "enclosure")) {
519                         my $file=$pagesources{$p};
520                         my $type=pagetype($file);
521                         if (defined $type) {
522                                 $itemtemplate->param(content => $pcontent);
523                         }
524                         else {
525                                 my $size=(srcfile_stat($file))[8];
526                                 my $mime="unknown";
527                                 eval q{use File::MimeInfo};
528                                 if (! $@) {
529                                         $mime = mimetype($file);
530                                 }
531                                 $itemtemplate->param(
532                                         enclosure => $u,
533                                         type => $mime,
534                                         length => $size,
535                                 );
536                         }
537                 }
538                 else {
539                         $itemtemplate->param(content => $pcontent);
540                 }
541
542                 run_hooks(pagetemplate => sub {
543                         shift->(page => $p, destpage => $page,
544                                 template => $itemtemplate);
545                 });
546
547                 $content.=$itemtemplate->output;
548                 $itemtemplate->clear_params;
549
550                 $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
551         }
552
553         my $template=template($feedtype."page.tmpl", blind_cache => 1);
554         $template->param(
555                 title => $page ne "index" ? pagetitle($page) : $config{wikiname},
556                 wikiname => $config{wikiname},
557                 pageurl => $url,
558                 content => $content,
559                 feeddesc => $feeddesc,
560                 guid => $guid,
561                 feeddate => date_3339($lasttime),
562                 feedurl => $feedurl,
563                 version => $IkiWiki::version,
564         );
565         run_hooks(pagetemplate => sub {
566                 shift->(page => $page, destpage => $page,
567                         template => $template);
568         });
569         
570         return $template->output;
571 } #}}}
572
573 sub pingurl (@) { #{{{
574         return unless @{$config{pingurl}} && %toping;
575
576         eval q{require RPC::XML::Client};
577         if ($@) {
578                 debug(gettext("RPC::XML::Client not found, not pinging"));
579                 return;
580         }
581
582         # daemonize here so slow pings don't slow down wiki updates
583         defined(my $pid = fork) or error("Can't fork: $!");
584         return if $pid;
585         chdir '/';
586         POSIX::setsid() or error("Can't start a new session: $!");
587         open STDIN, '/dev/null';
588         open STDOUT, '>/dev/null';
589         open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
590
591         # Don't need to keep a lock on the wiki as a daemon.
592         IkiWiki::unlockwiki();
593
594         foreach my $page (keys %toping) {
595                 my $title=pagetitle(basename($page), 0);
596                 my $url=urlto($page, "", 1);
597                 foreach my $pingurl (@{$config{pingurl}}) {
598                         debug("Pinging $pingurl for $page");
599                         eval {
600                                 my $client = RPC::XML::Client->new($pingurl);
601                                 my $req = RPC::XML::request->new('weblogUpdates.ping',
602                                         $title, $url);
603                                 my $res = $client->send_request($req);
604                                 if (! ref $res) {
605                                         error("Did not receive response to ping");
606                                 }
607                                 my $r=$res->value;
608                                 if (! exists $r->{flerror} || $r->{flerror}) {
609                                         error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
610                                 }
611                         };
612                         if ($@) {
613                                 error "Ping failed: $@";
614                         }
615                 }
616         }
617
618         exit 0; # daemon done
619 } #}}}
620
621 1