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