summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 0907df6a116eb7eecb5d53b479fd38bec77e7626 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use open qw{:utf8 :std};
  8. # Optimisation.
  9. use Memoize;
  10. memoize("abs2rel");
  11. memoize("pagespec_translate");
  12. use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
  13. %renderedfiles %pagesources %depends %hooks %forcerebuild};
  14. sub defaultconfig () { #{{{
  15. wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
  16. wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
  17. wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
  18. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  19. verbose => 0,
  20. wikiname => "wiki",
  21. default_pageext => "mdwn",
  22. cgi => 0,
  23. rcs => 'svn',
  24. notify => 0,
  25. url => '',
  26. cgiurl => '',
  27. historyurl => '',
  28. diffurl => '',
  29. anonok => 0,
  30. rss => 0,
  31. discussion => 1,
  32. rebuild => 0,
  33. refresh => 0,
  34. getctime => 0,
  35. w3mmode => 0,
  36. wrapper => undef,
  37. wrappermode => undef,
  38. svnrepo => undef,
  39. svnpath => "trunk",
  40. srcdir => undef,
  41. destdir => undef,
  42. pingurl => [],
  43. templatedir => "/usr/share/ikiwiki/templates",
  44. underlaydir => "/usr/share/ikiwiki/basewiki",
  45. setup => undef,
  46. adminuser => undef,
  47. adminemail => undef,
  48. plugin => [qw{mdwn inline htmlscrubber}],
  49. timeformat => '%c',
  50. locale => undef,
  51. } #}}}
  52. sub checkconfig () { #{{{
  53. # locale stuff; avoid LC_ALL since it overrides everything
  54. if (defined $ENV{LC_ALL}) {
  55. $ENV{LANG} = $ENV{LC_ALL};
  56. delete $ENV{LC_ALL};
  57. }
  58. if (defined $config{locale}) {
  59. eval q{use POSIX};
  60. $ENV{LANG} = $config{locale}
  61. if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
  62. }
  63. if ($config{w3mmode}) {
  64. eval q{use Cwd q{abs_path}};
  65. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  66. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  67. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  68. unless $config{cgiurl} =~ m!file:///!;
  69. $config{url}="file://".$config{destdir};
  70. }
  71. if ($config{cgi} && ! length $config{url}) {
  72. error("Must specify url to wiki with --url when using --cgi\n");
  73. }
  74. if ($config{rss} && ! length $config{url}) {
  75. error("Must specify url to wiki with --url when using --rss\n");
  76. }
  77. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  78. unless exists $config{wikistatedir};
  79. if ($config{rcs}) {
  80. eval qq{require IkiWiki::Rcs::$config{rcs}};
  81. if ($@) {
  82. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  83. }
  84. }
  85. else {
  86. require IkiWiki::Rcs::Stub;
  87. }
  88. run_hooks(checkconfig => sub { shift->() });
  89. } #}}}
  90. sub loadplugins () { #{{{
  91. foreach my $plugin (@{$config{plugin}}) {
  92. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  93. eval qq{use $mod};
  94. if ($@) {
  95. error("Failed to load plugin $mod: $@");
  96. }
  97. }
  98. run_hooks(getopt => sub { shift->() });
  99. if (grep /^-/, @ARGV) {
  100. print STDERR "Unknown option: $_\n"
  101. foreach grep /^-/, @ARGV;
  102. usage();
  103. }
  104. } #}}}
  105. sub error ($) { #{{{
  106. if ($config{cgi}) {
  107. print "Content-type: text/html\n\n";
  108. print misctemplate("Error", "<p>Error: @_</p>");
  109. }
  110. die @_;
  111. } #}}}
  112. sub debug ($) { #{{{
  113. return unless $config{verbose};
  114. if (! $config{cgi}) {
  115. print "@_\n";
  116. }
  117. else {
  118. print STDERR "@_\n";
  119. }
  120. } #}}}
  121. sub possibly_foolish_untaint ($) { #{{{
  122. my $tainted=shift;
  123. my ($untainted)=$tainted=~/(.*)/;
  124. return $untainted;
  125. } #}}}
  126. sub basename ($) { #{{{
  127. my $file=shift;
  128. $file=~s!.*/+!!;
  129. return $file;
  130. } #}}}
  131. sub dirname ($) { #{{{
  132. my $file=shift;
  133. $file=~s!/*[^/]+$!!;
  134. return $file;
  135. } #}}}
  136. sub pagetype ($) { #{{{
  137. my $page=shift;
  138. if ($page =~ /\.([^.]+)$/) {
  139. return $1 if exists $hooks{htmlize}{$1};
  140. }
  141. return undef;
  142. } #}}}
  143. sub pagename ($) { #{{{
  144. my $file=shift;
  145. my $type=pagetype($file);
  146. my $page=$file;
  147. $page=~s/\Q.$type\E*$// if defined $type;
  148. return $page;
  149. } #}}}
  150. sub htmlpage ($) { #{{{
  151. my $page=shift;
  152. return $page.".html";
  153. } #}}}
  154. sub srcfile ($) { #{{{
  155. my $file=shift;
  156. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  157. return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
  158. error("internal error: $file cannot be found");
  159. } #}}}
  160. sub readfile ($;$) { #{{{
  161. my $file=shift;
  162. my $binary=shift;
  163. if (-l $file) {
  164. error("cannot read a symlink ($file)");
  165. }
  166. local $/=undef;
  167. open (IN, $file) || error("failed to read $file: $!");
  168. binmode(IN) if ($binary);
  169. my $ret=<IN>;
  170. close IN;
  171. return $ret;
  172. } #}}}
  173. sub writefile ($$$;$) { #{{{
  174. my $file=shift; # can include subdirs
  175. my $destdir=shift; # directory to put file in
  176. my $content=shift;
  177. my $binary=shift;
  178. my $test=$file;
  179. while (length $test) {
  180. if (-l "$destdir/$test") {
  181. error("cannot write to a symlink ($test)");
  182. }
  183. $test=dirname($test);
  184. }
  185. my $dir=dirname("$destdir/$file");
  186. if (! -d $dir) {
  187. my $d="";
  188. foreach my $s (split(m!/+!, $dir)) {
  189. $d.="$s/";
  190. if (! -d $d) {
  191. mkdir($d) || error("failed to create directory $d: $!");
  192. }
  193. }
  194. }
  195. open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
  196. binmode(OUT) if ($binary);
  197. print OUT $content;
  198. close OUT;
  199. } #}}}
  200. sub bestlink ($$) { #{{{
  201. # Given a page and the text of a link on the page, determine which
  202. # existing page that link best points to. Prefers pages under a
  203. # subdirectory with the same name as the source page, failing that
  204. # goes down the directory tree to the base looking for matching
  205. # pages.
  206. my $page=shift;
  207. my $link=lc(shift);
  208. my $cwd=$page;
  209. do {
  210. my $l=$cwd;
  211. $l.="/" if length $l;
  212. $l.=$link;
  213. if (exists $links{$l}) {
  214. #debug("for $page, \"$link\", use $l");
  215. return $l;
  216. }
  217. } while $cwd=~s!/?[^/]+$!!;
  218. #print STDERR "warning: page $page, broken link: $link\n";
  219. return "";
  220. } #}}}
  221. sub isinlinableimage ($) { #{{{
  222. my $file=shift;
  223. $file=~/\.(png|gif|jpg|jpeg)$/i;
  224. } #}}}
  225. sub pagetitle ($) { #{{{
  226. my $page=shift;
  227. $page=~s/__(\d+)__/&#$1;/g;
  228. $page=~y/_/ /;
  229. return $page;
  230. } #}}}
  231. sub titlepage ($) { #{{{
  232. my $title=shift;
  233. $title=~y/ /_/;
  234. $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
  235. return $title;
  236. } #}}}
  237. sub cgiurl (@) { #{{{
  238. my %params=@_;
  239. return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
  240. } #}}}
  241. sub styleurl (;$) { #{{{
  242. my $page=shift;
  243. return "$config{url}/style.css" if ! defined $page;
  244. $page=~s/[^\/]+$//;
  245. $page=~s/[^\/]+\//..\//g;
  246. return $page."style.css";
  247. } #}}}
  248. sub abs2rel ($$) { #{{{
  249. # Work around very innefficient behavior in File::Spec if abs2rel
  250. # is passed two relative paths. It's much faster if paths are
  251. # absolute!
  252. my $path="/".shift;
  253. my $base="/".shift;
  254. require File::Spec;
  255. my $ret=File::Spec->abs2rel($path, $base);
  256. $ret=~s/^// if defined $ret;
  257. return $ret;
  258. } #}}}
  259. sub htmllink ($$$;$$$) { #{{{
  260. my $lpage=shift; # the page doing the linking
  261. my $page=shift; # the page that will contain the link (different for inline)
  262. my $link=shift;
  263. my $noimageinline=shift; # don't turn links into inline html images
  264. my $forcesubpage=shift; # force a link to a subpage
  265. my $linktext=shift; # set to force the link text to something
  266. my $bestlink;
  267. if (! $forcesubpage) {
  268. $bestlink=bestlink($lpage, $link);
  269. }
  270. else {
  271. $bestlink="$lpage/".lc($link);
  272. }
  273. $linktext=pagetitle(basename($link)) unless defined $linktext;
  274. return $linktext if length $bestlink && $page eq $bestlink;
  275. # TODO BUG: %renderedfiles may not have it, if the linked to page
  276. # was also added and isn't yet rendered! Note that this bug is
  277. # masked by the bug that makes all new files be rendered twice.
  278. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  279. $bestlink=htmlpage($bestlink);
  280. }
  281. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  282. return "<span><a href=\"".
  283. cgiurl(do => "create", page => $link, from => $page).
  284. "\">?</a>$linktext</span>"
  285. }
  286. $bestlink=abs2rel($bestlink, dirname($page));
  287. if (! $noimageinline && isinlinableimage($bestlink)) {
  288. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  289. }
  290. return "<a href=\"$bestlink\">$linktext</a>";
  291. } #}}}
  292. sub indexlink () { #{{{
  293. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  294. } #}}}
  295. sub lockwiki () { #{{{
  296. # Take an exclusive lock on the wiki to prevent multiple concurrent
  297. # run issues. The lock will be dropped on program exit.
  298. if (! -d $config{wikistatedir}) {
  299. mkdir($config{wikistatedir});
  300. }
  301. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  302. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  303. if (! flock(WIKILOCK, 2 | 4)) {
  304. debug("wiki seems to be locked, waiting for lock");
  305. my $wait=600; # arbitrary, but don't hang forever to
  306. # prevent process pileup
  307. for (1..600) {
  308. return if flock(WIKILOCK, 2 | 4);
  309. sleep 1;
  310. }
  311. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  312. }
  313. } #}}}
  314. sub unlockwiki () { #{{{
  315. close WIKILOCK;
  316. } #}}}
  317. sub loadindex () { #{{{
  318. open (IN, "$config{wikistatedir}/index") || return;
  319. while (<IN>) {
  320. $_=possibly_foolish_untaint($_);
  321. chomp;
  322. my %items;
  323. $items{link}=[];
  324. foreach my $i (split(/ /, $_)) {
  325. my ($item, $val)=split(/=/, $i, 2);
  326. push @{$items{$item}}, decode_entities($val);
  327. }
  328. next unless exists $items{src}; # skip bad lines for now
  329. my $page=pagename($items{src}[0]);
  330. if (! $config{rebuild}) {
  331. $pagesources{$page}=$items{src}[0];
  332. $oldpagemtime{$page}=$items{mtime}[0];
  333. $oldlinks{$page}=[@{$items{link}}];
  334. $links{$page}=[@{$items{link}}];
  335. $depends{$page}=$items{depends}[0] if exists $items{depends};
  336. $renderedfiles{$page}=$items{dest}[0];
  337. }
  338. $pagectime{$page}=$items{ctime}[0];
  339. }
  340. close IN;
  341. } #}}}
  342. sub saveindex () { #{{{
  343. run_hooks(savestate => sub { shift->() });
  344. if (! -d $config{wikistatedir}) {
  345. mkdir($config{wikistatedir});
  346. }
  347. open (OUT, ">$config{wikistatedir}/index") ||
  348. error("cannot write to $config{wikistatedir}/index: $!");
  349. foreach my $page (keys %oldpagemtime) {
  350. next unless $oldpagemtime{$page};
  351. my $line="mtime=$oldpagemtime{$page} ".
  352. "ctime=$pagectime{$page} ".
  353. "src=$pagesources{$page} ".
  354. "dest=$renderedfiles{$page}";
  355. $line.=" link=$_" foreach @{$links{$page}};
  356. if (exists $depends{$page}) {
  357. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  358. }
  359. print OUT $line."\n";
  360. }
  361. close OUT;
  362. } #}}}
  363. sub template_params (@) { #{{{
  364. my $filename=shift;
  365. require HTML::Template;
  366. return filter => sub {
  367. my $text_ref = shift;
  368. $$text_ref=&Encode::decode_utf8($$text_ref);
  369. },
  370. filename => "$config{templatedir}/$filename",
  371. loop_context_vars => 1,
  372. @_;
  373. } #}}}
  374. sub template ($;@) { #{{{
  375. HTML::Template->new(template_params(@_));
  376. } #}}}
  377. sub misctemplate ($$) { #{{{
  378. my $title=shift;
  379. my $pagebody=shift;
  380. my $template=template("misc.tmpl");
  381. $template->param(
  382. title => $title,
  383. indexlink => indexlink(),
  384. wikiname => $config{wikiname},
  385. pagebody => $pagebody,
  386. styleurl => styleurl(),
  387. baseurl => "$config{url}/",
  388. );
  389. return $template->output;
  390. }#}}}
  391. sub hook (@) { # {{{
  392. my %param=@_;
  393. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  394. error "hook requires type, call, and id parameters";
  395. }
  396. $hooks{$param{type}}{$param{id}}=\%param;
  397. } # }}}
  398. sub run_hooks ($$) { # {{{
  399. # Calls the given sub for each hook of the given type,
  400. # passing it the hook function to call.
  401. my $type=shift;
  402. my $sub=shift;
  403. if (exists $hooks{$type}) {
  404. foreach my $id (keys %{$hooks{$type}}) {
  405. $sub->($hooks{$type}{$id}{call});
  406. }
  407. }
  408. } #}}}
  409. sub globlist_to_pagespec ($) { #{{{
  410. my @globlist=split(' ', shift);
  411. my (@spec, @skip);
  412. foreach my $glob (@globlist) {
  413. if ($glob=~/^!(.*)/) {
  414. push @skip, $glob;
  415. }
  416. else {
  417. push @spec, $glob;
  418. }
  419. }
  420. my $spec=join(" or ", @spec);
  421. if (@skip) {
  422. my $skip=join(" and ", @skip);
  423. if (length $spec) {
  424. $spec="$skip and ($spec)";
  425. }
  426. else {
  427. $spec=$skip;
  428. }
  429. }
  430. return $spec;
  431. } #}}}
  432. sub is_globlist ($) { #{{{
  433. my $s=shift;
  434. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  435. } #}}}
  436. sub safequote ($) { #{{{
  437. my $s=shift;
  438. $s=~s/[{}]//g;
  439. return "q{$s}";
  440. } #}}}
  441. sub pagespec_merge ($$) { #{{{
  442. my $a=shift;
  443. my $b=shift;
  444. # Support for old-style GlobLists.
  445. if (is_globlist($a)) {
  446. $a=globlist_to_pagespec($a);
  447. }
  448. if (is_globlist($b)) {
  449. $b=globlist_to_pagespec($b);
  450. }
  451. return "($a) or ($b)";
  452. } #}}}
  453. sub pagespec_translate ($) { #{{{
  454. # This assumes that $page is in scope in the function
  455. # that evalulates the translated pagespec code.
  456. my $spec=shift;
  457. # Support for old-style GlobLists.
  458. if (is_globlist($spec)) {
  459. $spec=globlist_to_pagespec($spec);
  460. }
  461. # Convert spec to perl code.
  462. my $code="";
  463. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  464. my $word=$1;
  465. if (lc $word eq "and") {
  466. $code.=" &&";
  467. }
  468. elsif (lc $word eq "or") {
  469. $code.=" ||";
  470. }
  471. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  472. $code.=" ".$word;
  473. }
  474. elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
  475. $code.=" match_$1(\$page, ".safequote($2).")";
  476. }
  477. else {
  478. $code.=" match_glob(\$page, ".safequote($word).")";
  479. }
  480. }
  481. return $code;
  482. } #}}}
  483. sub pagespec_match ($$) { #{{{
  484. my $page=shift;
  485. my $spec=shift;
  486. return eval pagespec_translate($spec);
  487. } #}}}
  488. sub match_glob ($$) { #{{{
  489. my $page=shift;
  490. my $glob=shift;
  491. # turn glob into safe regexp
  492. $glob=quotemeta($glob);
  493. $glob=~s/\\\*/.*/g;
  494. $glob=~s/\\\?/./g;
  495. return $page=~/^$glob$/i;
  496. } #}}}
  497. sub match_link ($$) { #{{{
  498. my $page=shift;
  499. my $link=shift;
  500. my $links = $links{$page} or return undef;
  501. foreach my $p (@$links) {
  502. return 1 if lc $p eq $link;
  503. }
  504. return 0;
  505. } #}}}
  506. sub match_backlink ($$) { #{{{
  507. match_link(pop, pop);
  508. } #}}}
  509. sub match_created_before ($$) { #{{{
  510. my $page=shift;
  511. my $testpage=shift;
  512. if (exists $pagectime{$testpage}) {
  513. return $pagectime{$page} < $pagectime{$testpage};
  514. }
  515. else {
  516. return 0;
  517. }
  518. } #}}}
  519. sub match_created_after ($$) { #{{{
  520. my $page=shift;
  521. my $testpage=shift;
  522. if (exists $pagectime{$testpage}) {
  523. return $pagectime{$page} > $pagectime{$testpage};
  524. }
  525. else {
  526. return 0;
  527. }
  528. } #}}}
  529. sub match_creation_day ($$) { #{{{
  530. return ((gmtime($pagectime{shift()}))[3] == shift);
  531. } #}}}
  532. sub match_creation_month ($$) { #{{{
  533. return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
  534. } #}}}
  535. sub match_creation_year ($$) { #{{{
  536. return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
  537. } #}}}
  538. 1