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