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