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