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