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