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