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