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