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