summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 560647e067f224bd62d2c9cd49b9c17359933b9f (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 %pagecase
  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=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. return $l;
  215. }
  216. elsif (exists $pagecase{lc $l}) {
  217. return $pagecase{lc $l};
  218. }
  219. } while $cwd=~s!/?[^/]+$!!;
  220. #print STDERR "warning: page $page, broken link: $link\n";
  221. return "";
  222. } #}}}
  223. sub isinlinableimage ($) { #{{{
  224. my $file=shift;
  225. $file=~/\.(png|gif|jpg|jpeg)$/i;
  226. } #}}}
  227. sub pagetitle ($) { #{{{
  228. my $page=shift;
  229. $page=~s/__(\d+)__/&#$1;/g;
  230. $page=~y/_/ /;
  231. return $page;
  232. } #}}}
  233. sub titlepage ($) { #{{{
  234. my $title=shift;
  235. $title=~y/ /_/;
  236. $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
  237. return $title;
  238. } #}}}
  239. sub cgiurl (@) { #{{{
  240. my %params=@_;
  241. return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
  242. } #}}}
  243. sub styleurl (;$) { #{{{
  244. my $page=shift;
  245. return "$config{url}/style.css" if ! defined $page;
  246. $page=~s/[^\/]+$//;
  247. $page=~s/[^\/]+\//..\//g;
  248. return $page."style.css";
  249. } #}}}
  250. sub abs2rel ($$) { #{{{
  251. # Work around very innefficient behavior in File::Spec if abs2rel
  252. # is passed two relative paths. It's much faster if paths are
  253. # absolute!
  254. my $path="/".shift;
  255. my $base="/".shift;
  256. require File::Spec;
  257. my $ret=File::Spec->abs2rel($path, $base);
  258. $ret=~s/^// if defined $ret;
  259. return $ret;
  260. } #}}}
  261. sub htmllink ($$$;$$$) { #{{{
  262. my $lpage=shift; # the page doing the linking
  263. my $page=shift; # the page that will contain the link (different for inline)
  264. my $link=shift;
  265. my $noimageinline=shift; # don't turn links into inline html images
  266. my $forcesubpage=shift; # force a link to a subpage
  267. my $linktext=shift; # set to force the link text to something
  268. my $bestlink;
  269. if (! $forcesubpage) {
  270. $bestlink=bestlink($lpage, $link);
  271. }
  272. else {
  273. $bestlink="$lpage/".lc($link);
  274. }
  275. $linktext=pagetitle(basename($link)) unless defined $linktext;
  276. return $linktext if length $bestlink && $page eq $bestlink;
  277. # TODO BUG: %renderedfiles may not have it, if the linked to page
  278. # was also added and isn't yet rendered! Note that this bug is
  279. # masked by the bug that makes all new files be rendered twice.
  280. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  281. $bestlink=htmlpage($bestlink);
  282. }
  283. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  284. return "<span><a href=\"".
  285. cgiurl(do => "create", page => lc($link), from => $page).
  286. "\">?</a>$linktext</span>"
  287. }
  288. $bestlink=abs2rel($bestlink, dirname($page));
  289. if (! $noimageinline && isinlinableimage($bestlink)) {
  290. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  291. }
  292. return "<a href=\"$bestlink\">$linktext</a>";
  293. } #}}}
  294. sub indexlink () { #{{{
  295. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  296. } #}}}
  297. sub lockwiki () { #{{{
  298. # Take an exclusive lock on the wiki to prevent multiple concurrent
  299. # run issues. The lock will be dropped on program exit.
  300. if (! -d $config{wikistatedir}) {
  301. mkdir($config{wikistatedir});
  302. }
  303. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  304. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  305. if (! flock(WIKILOCK, 2 | 4)) {
  306. debug("wiki seems to be locked, waiting for lock");
  307. my $wait=600; # arbitrary, but don't hang forever to
  308. # prevent process pileup
  309. for (1..600) {
  310. return if flock(WIKILOCK, 2 | 4);
  311. sleep 1;
  312. }
  313. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  314. }
  315. } #}}}
  316. sub unlockwiki () { #{{{
  317. close WIKILOCK;
  318. } #}}}
  319. sub loadindex () { #{{{
  320. open (IN, "$config{wikistatedir}/index") || return;
  321. while (<IN>) {
  322. $_=possibly_foolish_untaint($_);
  323. chomp;
  324. my %items;
  325. $items{link}=[];
  326. foreach my $i (split(/ /, $_)) {
  327. my ($item, $val)=split(/=/, $i, 2);
  328. push @{$items{$item}}, decode_entities($val);
  329. }
  330. next unless exists $items{src}; # skip bad lines for now
  331. my $page=pagename($items{src}[0]);
  332. if (! $config{rebuild}) {
  333. $pagesources{$page}=$items{src}[0];
  334. $oldpagemtime{$page}=$items{mtime}[0];
  335. $oldlinks{$page}=[@{$items{link}}];
  336. $links{$page}=[@{$items{link}}];
  337. $depends{$page}=$items{depends}[0] if exists $items{depends};
  338. $renderedfiles{$page}=$items{dest}[0];
  339. $pagecase{lc $page}=$page;
  340. }
  341. $pagectime{$page}=$items{ctime}[0];
  342. }
  343. close IN;
  344. } #}}}
  345. sub saveindex () { #{{{
  346. run_hooks(savestate => sub { shift->() });
  347. if (! -d $config{wikistatedir}) {
  348. mkdir($config{wikistatedir});
  349. }
  350. open (OUT, ">$config{wikistatedir}/index") ||
  351. error("cannot write to $config{wikistatedir}/index: $!");
  352. foreach my $page (keys %oldpagemtime) {
  353. next unless $oldpagemtime{$page};
  354. my $line="mtime=$oldpagemtime{$page} ".
  355. "ctime=$pagectime{$page} ".
  356. "src=$pagesources{$page} ".
  357. "dest=$renderedfiles{$page}";
  358. $line.=" link=$_" foreach @{$links{$page}};
  359. if (exists $depends{$page}) {
  360. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  361. }
  362. print OUT $line."\n";
  363. }
  364. close OUT;
  365. } #}}}
  366. sub template_params (@) { #{{{
  367. my $filename=shift;
  368. require HTML::Template;
  369. return filter => sub {
  370. my $text_ref = shift;
  371. $$text_ref=&Encode::decode_utf8($$text_ref);
  372. },
  373. filename => "$config{templatedir}/$filename",
  374. loop_context_vars => 1,
  375. die_on_bad_params => 0,
  376. @_;
  377. } #}}}
  378. sub template ($;@) { #{{{
  379. HTML::Template->new(template_params(@_));
  380. } #}}}
  381. sub misctemplate ($$) { #{{{
  382. my $title=shift;
  383. my $pagebody=shift;
  384. my $template=template("misc.tmpl");
  385. $template->param(
  386. title => $title,
  387. indexlink => indexlink(),
  388. wikiname => $config{wikiname},
  389. pagebody => $pagebody,
  390. styleurl => styleurl(),
  391. baseurl => "$config{url}/",
  392. );
  393. return $template->output;
  394. }#}}}
  395. sub hook (@) { # {{{
  396. my %param=@_;
  397. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  398. error "hook requires type, call, and id parameters";
  399. }
  400. $hooks{$param{type}}{$param{id}}=\%param;
  401. } # }}}
  402. sub run_hooks ($$) { # {{{
  403. # Calls the given sub for each hook of the given type,
  404. # passing it the hook function to call.
  405. my $type=shift;
  406. my $sub=shift;
  407. if (exists $hooks{$type}) {
  408. foreach my $id (keys %{$hooks{$type}}) {
  409. $sub->($hooks{$type}{$id}{call});
  410. }
  411. }
  412. } #}}}
  413. sub globlist_to_pagespec ($) { #{{{
  414. my @globlist=split(' ', shift);
  415. my (@spec, @skip);
  416. foreach my $glob (@globlist) {
  417. if ($glob=~/^!(.*)/) {
  418. push @skip, $glob;
  419. }
  420. else {
  421. push @spec, $glob;
  422. }
  423. }
  424. my $spec=join(" or ", @spec);
  425. if (@skip) {
  426. my $skip=join(" and ", @skip);
  427. if (length $spec) {
  428. $spec="$skip and ($spec)";
  429. }
  430. else {
  431. $spec=$skip;
  432. }
  433. }
  434. return $spec;
  435. } #}}}
  436. sub is_globlist ($) { #{{{
  437. my $s=shift;
  438. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  439. } #}}}
  440. sub safequote ($) { #{{{
  441. my $s=shift;
  442. $s=~s/[{}]//g;
  443. return "q{$s}";
  444. } #}}}
  445. sub pagespec_merge ($$) { #{{{
  446. my $a=shift;
  447. my $b=shift;
  448. # Support for old-style GlobLists.
  449. if (is_globlist($a)) {
  450. $a=globlist_to_pagespec($a);
  451. }
  452. if (is_globlist($b)) {
  453. $b=globlist_to_pagespec($b);
  454. }
  455. return "($a) or ($b)";
  456. } #}}}
  457. sub pagespec_translate ($) { #{{{
  458. # This assumes that $page is in scope in the function
  459. # that evalulates the translated pagespec code.
  460. my $spec=shift;
  461. # Support for old-style GlobLists.
  462. if (is_globlist($spec)) {
  463. $spec=globlist_to_pagespec($spec);
  464. }
  465. # Convert spec to perl code.
  466. my $code="";
  467. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  468. my $word=$1;
  469. if (lc $word eq "and") {
  470. $code.=" &&";
  471. }
  472. elsif (lc $word eq "or") {
  473. $code.=" ||";
  474. }
  475. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  476. $code.=" ".$word;
  477. }
  478. elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
  479. $code.=" match_$1(\$page, ".safequote($2).")";
  480. }
  481. else {
  482. $code.=" match_glob(\$page, ".safequote($word).")";
  483. }
  484. }
  485. return $code;
  486. } #}}}
  487. sub pagespec_match ($$) { #{{{
  488. my $page=shift;
  489. my $spec=shift;
  490. return eval pagespec_translate($spec);
  491. } #}}}
  492. sub match_glob ($$) { #{{{
  493. my $page=shift;
  494. my $glob=shift;
  495. # turn glob into safe regexp
  496. $glob=quotemeta($glob);
  497. $glob=~s/\\\*/.*/g;
  498. $glob=~s/\\\?/./g;
  499. return $page=~/^$glob$/i;
  500. } #}}}
  501. sub match_link ($$) { #{{{
  502. my $page=shift;
  503. my $link=lc(shift);
  504. my $links = $links{$page} or return undef;
  505. foreach my $p (@$links) {
  506. return 1 if lc $p eq $link;
  507. }
  508. return 0;
  509. } #}}}
  510. sub match_backlink ($$) { #{{{
  511. match_link(pop, pop);
  512. } #}}}
  513. sub match_created_before ($$) { #{{{
  514. my $page=shift;
  515. my $testpage=shift;
  516. if (exists $pagectime{$testpage}) {
  517. return $pagectime{$page} < $pagectime{$testpage};
  518. }
  519. else {
  520. return 0;
  521. }
  522. } #}}}
  523. sub match_created_after ($$) { #{{{
  524. my $page=shift;
  525. my $testpage=shift;
  526. if (exists $pagectime{$testpage}) {
  527. return $pagectime{$page} > $pagectime{$testpage};
  528. }
  529. else {
  530. return 0;
  531. }
  532. } #}}}
  533. sub match_creation_day ($$) { #{{{
  534. return ((gmtime($pagectime{shift()}))[3] == shift);
  535. } #}}}
  536. sub match_creation_month ($$) { #{{{
  537. return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
  538. } #}}}
  539. sub match_creation_year ($$) { #{{{
  540. return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
  541. } #}}}
  542. 1