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