summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: ad4d26741af22a5a0f087917ebc8334e819f7398 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use URI::Escape q{uri_escape_utf8};
  8. use POSIX;
  9. use open qw{:utf8 :std};
  10. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  11. %renderedfiles %oldrenderedfiles %pagesources %destsources
  12. %depends %hooks %forcerebuild $gettext_obj};
  13. use Exporter q{import};
  14. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  15. bestlink htmllink readfile writefile pagetype srcfile pagename
  16. displaytime will_render gettext urlto targetpage
  17. add_underlay
  18. %config %links %renderedfiles %pagesources %destsources);
  19. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  20. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  21. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  22. # Optimisation.
  23. use Memoize;
  24. memoize("abs2rel");
  25. memoize("pagespec_translate");
  26. memoize("file_pruned");
  27. sub defaultconfig () { #{{{
  28. return
  29. wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
  30. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  31. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  32. qr/(^|\/)_MTN\//,
  33. qr/\.dpkg-tmp$/],
  34. wiki_link_regexp => qr{
  35. \[\[ # beginning of link
  36. (?:
  37. ([^\]\|\n\s]+) # 1: link text
  38. \| # followed by '|'
  39. )? # optional
  40. ([^\s\]#]+) # 2: page to link to
  41. (?:
  42. \# # '#', beginning of anchor
  43. ([^\s\]]+) # 3: anchor text
  44. )? # optional
  45. \]\] # end of link
  46. }x,
  47. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  48. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  49. verbose => 0,
  50. syslog => 0,
  51. wikiname => "wiki",
  52. default_pageext => "mdwn",
  53. htmlext => "html",
  54. cgi => 0,
  55. post_commit => 0,
  56. rcs => '',
  57. notify => 0,
  58. url => '',
  59. cgiurl => '',
  60. historyurl => '',
  61. diffurl => '',
  62. rss => 0,
  63. atom => 0,
  64. discussion => 1,
  65. rebuild => 0,
  66. refresh => 0,
  67. getctime => 0,
  68. w3mmode => 0,
  69. wrapper => undef,
  70. wrappermode => undef,
  71. svnrepo => undef,
  72. svnpath => "trunk",
  73. gitorigin_branch => "origin",
  74. gitmaster_branch => "master",
  75. srcdir => undef,
  76. destdir => undef,
  77. pingurl => [],
  78. templatedir => "$installdir/share/ikiwiki/templates",
  79. underlaydir => "$installdir/share/ikiwiki/basewiki",
  80. underlaydirs => [],
  81. setup => undef,
  82. adminuser => undef,
  83. adminemail => undef,
  84. plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
  85. lockedit conditional}],
  86. libdir => undef,
  87. timeformat => '%c',
  88. locale => undef,
  89. sslcookie => 0,
  90. httpauth => 0,
  91. userdir => "",
  92. usedirs => 1,
  93. numbacklinks => 10,
  94. account_creation_password => "",
  95. } #}}}
  96. sub checkconfig () { #{{{
  97. # locale stuff; avoid LC_ALL since it overrides everything
  98. if (defined $ENV{LC_ALL}) {
  99. $ENV{LANG} = $ENV{LC_ALL};
  100. delete $ENV{LC_ALL};
  101. }
  102. if (defined $config{locale}) {
  103. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  104. $ENV{LANG}=$config{locale};
  105. $gettext_obj=undef;
  106. }
  107. }
  108. if ($config{w3mmode}) {
  109. eval q{use Cwd q{abs_path}};
  110. error($@) if $@;
  111. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  112. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  113. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  114. unless $config{cgiurl} =~ m!file:///!;
  115. $config{url}="file://".$config{destdir};
  116. }
  117. if ($config{cgi} && ! length $config{url}) {
  118. error(gettext("Must specify url to wiki with --url when using --cgi"));
  119. }
  120. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  121. unless exists $config{wikistatedir};
  122. if ($config{rcs}) {
  123. eval qq{use IkiWiki::Rcs::$config{rcs}};
  124. if ($@) {
  125. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  126. }
  127. }
  128. else {
  129. require IkiWiki::Rcs::Stub;
  130. }
  131. run_hooks(checkconfig => sub { shift->() });
  132. return 1;
  133. } #}}}
  134. sub loadplugins () { #{{{
  135. if (defined $config{libdir}) {
  136. unshift @INC, possibly_foolish_untaint($config{libdir});
  137. }
  138. loadplugin($_) foreach @{$config{plugin}};
  139. run_hooks(getopt => sub { shift->() });
  140. if (grep /^-/, @ARGV) {
  141. print STDERR "Unknown option: $_\n"
  142. foreach grep /^-/, @ARGV;
  143. usage();
  144. }
  145. return 1;
  146. } #}}}
  147. sub loadplugin ($) { #{{{
  148. my $plugin=shift;
  149. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  150. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  151. "$installdir/lib/ikiwiki") {
  152. if (defined $dir && -x "$dir/plugins/$plugin") {
  153. require IkiWiki::Plugin::external;
  154. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  155. return 1;
  156. }
  157. }
  158. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  159. eval qq{use $mod};
  160. if ($@) {
  161. error("Failed to load plugin $mod: $@");
  162. }
  163. return 1;
  164. } #}}}
  165. sub error ($;$) { #{{{
  166. my $message=shift;
  167. my $cleaner=shift;
  168. if ($config{cgi}) {
  169. print "Content-type: text/html\n\n";
  170. print misctemplate(gettext("Error"),
  171. "<p>".gettext("Error").": $message</p>");
  172. }
  173. log_message('err' => $message) if $config{syslog};
  174. if (defined $cleaner) {
  175. $cleaner->();
  176. }
  177. die $message."\n";
  178. } #}}}
  179. sub debug ($) { #{{{
  180. return unless $config{verbose};
  181. return log_message(debug => @_);
  182. } #}}}
  183. my $log_open=0;
  184. sub log_message ($$) { #{{{
  185. my $type=shift;
  186. if ($config{syslog}) {
  187. require Sys::Syslog;
  188. if (! $log_open) {
  189. Sys::Syslog::setlogsock('unix');
  190. Sys::Syslog::openlog('ikiwiki', '', 'user');
  191. $log_open=1;
  192. }
  193. return eval {
  194. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  195. };
  196. }
  197. elsif (! $config{cgi}) {
  198. return print "@_\n";
  199. }
  200. else {
  201. return print STDERR "@_\n";
  202. }
  203. } #}}}
  204. sub possibly_foolish_untaint ($) { #{{{
  205. my $tainted=shift;
  206. my ($untainted)=$tainted=~/(.*)/s;
  207. return $untainted;
  208. } #}}}
  209. sub basename ($) { #{{{
  210. my $file=shift;
  211. $file=~s!.*/+!!;
  212. return $file;
  213. } #}}}
  214. sub dirname ($) { #{{{
  215. my $file=shift;
  216. $file=~s!/*[^/]+$!!;
  217. return $file;
  218. } #}}}
  219. sub pagetype ($) { #{{{
  220. my $page=shift;
  221. if ($page =~ /\.([^.]+)$/) {
  222. return $1 if exists $hooks{htmlize}{$1};
  223. }
  224. return;
  225. } #}}}
  226. sub pagename ($) { #{{{
  227. my $file=shift;
  228. my $type=pagetype($file);
  229. my $page=$file;
  230. $page=~s/\Q.$type\E*$// if defined $type;
  231. return $page;
  232. } #}}}
  233. sub targetpage ($$) { #{{{
  234. my $page=shift;
  235. my $ext=shift;
  236. if (! $config{usedirs} || $page =~ /^index$/ ) {
  237. return $page.".".$ext;
  238. } else {
  239. return $page."/index.".$ext;
  240. }
  241. } #}}}
  242. sub htmlpage ($) { #{{{
  243. my $page=shift;
  244. return targetpage($page, $config{htmlext});
  245. } #}}}
  246. sub srcfile ($) { #{{{
  247. my $file=shift;
  248. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  249. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  250. return "$dir/$file" if -e "$dir/$file";
  251. }
  252. error("internal error: $file cannot be found in $config{srcdir} or underlay");
  253. return;
  254. } #}}}
  255. sub add_underlay ($) { #{{{
  256. my $dir=shift;
  257. if ($dir=~/^\//) {
  258. unshift @{$config{underlaydirs}}, $dir;
  259. }
  260. else {
  261. unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
  262. }
  263. return 1;
  264. } #}}}
  265. sub readfile ($;$$) { #{{{
  266. my $file=shift;
  267. my $binary=shift;
  268. my $wantfd=shift;
  269. if (-l $file) {
  270. error("cannot read a symlink ($file)");
  271. }
  272. local $/=undef;
  273. open (my $in, "<", $file) || error("failed to read $file: $!");
  274. binmode($in) if ($binary);
  275. return \*$in if $wantfd;
  276. my $ret=<$in>;
  277. close $in || error("failed to read $file: $!");
  278. return $ret;
  279. } #}}}
  280. sub writefile ($$$;$$) { #{{{
  281. my $file=shift; # can include subdirs
  282. my $destdir=shift; # directory to put file in
  283. my $content=shift;
  284. my $binary=shift;
  285. my $writer=shift;
  286. my $test=$file;
  287. while (length $test) {
  288. if (-l "$destdir/$test") {
  289. error("cannot write to a symlink ($test)");
  290. }
  291. $test=dirname($test);
  292. }
  293. my $newfile="$destdir/$file.ikiwiki-new";
  294. if (-l $newfile) {
  295. error("cannot write to a symlink ($newfile)");
  296. }
  297. my $dir=dirname($newfile);
  298. if (! -d $dir) {
  299. my $d="";
  300. foreach my $s (split(m!/+!, $dir)) {
  301. $d.="$s/";
  302. if (! -d $d) {
  303. mkdir($d) || error("failed to create directory $d: $!");
  304. }
  305. }
  306. }
  307. my $cleanup = sub { unlink($newfile) };
  308. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  309. binmode($out) if ($binary);
  310. if ($writer) {
  311. $writer->(\*$out, $cleanup);
  312. }
  313. else {
  314. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  315. }
  316. close $out || error("failed saving $newfile: $!", $cleanup);
  317. rename($newfile, "$destdir/$file") ||
  318. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  319. return 1;
  320. } #}}}
  321. my %cleared;
  322. sub will_render ($$;$) { #{{{
  323. my $page=shift;
  324. my $dest=shift;
  325. my $clear=shift;
  326. # Important security check.
  327. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  328. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  329. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  330. }
  331. if (! $clear || $cleared{$page}) {
  332. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  333. }
  334. else {
  335. foreach my $old (@{$renderedfiles{$page}}) {
  336. delete $destsources{$old};
  337. }
  338. $renderedfiles{$page}=[$dest];
  339. $cleared{$page}=1;
  340. }
  341. $destsources{$dest}=$page;
  342. return 1;
  343. } #}}}
  344. sub bestlink ($$) { #{{{
  345. my $page=shift;
  346. my $link=shift;
  347. my $cwd=$page;
  348. if ($link=~s/^\/+//) {
  349. # absolute links
  350. $cwd="";
  351. }
  352. do {
  353. my $l=$cwd;
  354. $l.="/" if length $l;
  355. $l.=$link;
  356. if (exists $links{$l}) {
  357. return $l;
  358. }
  359. elsif (exists $pagecase{lc $l}) {
  360. return $pagecase{lc $l};
  361. }
  362. } while $cwd=~s!/?[^/]+$!!;
  363. if (length $config{userdir}) {
  364. my $l = "$config{userdir}/".lc($link);
  365. if (exists $links{$l}) {
  366. return $l;
  367. }
  368. elsif (exists $pagecase{lc $l}) {
  369. return $pagecase{lc $l};
  370. }
  371. }
  372. #print STDERR "warning: page $page, broken link: $link\n";
  373. return "";
  374. } #}}}
  375. sub isinlinableimage ($) { #{{{
  376. my $file=shift;
  377. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  378. } #}}}
  379. sub pagetitle ($;$) { #{{{
  380. my $page=shift;
  381. my $unescaped=shift;
  382. if ($unescaped) {
  383. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  384. }
  385. else {
  386. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  387. }
  388. return $page;
  389. } #}}}
  390. sub titlepage ($) { #{{{
  391. my $title=shift;
  392. $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  393. return $title;
  394. } #}}}
  395. sub linkpage ($) { #{{{
  396. my $link=shift;
  397. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  398. return $link;
  399. } #}}}
  400. sub cgiurl (@) { #{{{
  401. my %params=@_;
  402. return $config{cgiurl}."?".
  403. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  404. } #}}}
  405. sub baseurl (;$) { #{{{
  406. my $page=shift;
  407. return "$config{url}/" if ! defined $page;
  408. $page=htmlpage($page);
  409. $page=~s/[^\/]+$//;
  410. $page=~s/[^\/]+\//..\//g;
  411. return $page;
  412. } #}}}
  413. sub abs2rel ($$) { #{{{
  414. # Work around very innefficient behavior in File::Spec if abs2rel
  415. # is passed two relative paths. It's much faster if paths are
  416. # absolute! (Debian bug #376658; fixed in debian unstable now)
  417. my $path="/".shift;
  418. my $base="/".shift;
  419. require File::Spec;
  420. my $ret=File::Spec->abs2rel($path, $base);
  421. $ret=~s/^// if defined $ret;
  422. return $ret;
  423. } #}}}
  424. sub displaytime ($;$) { #{{{
  425. my $time=shift;
  426. my $format=shift;
  427. if (! defined $format) {
  428. $format=$config{timeformat};
  429. }
  430. # strftime doesn't know about encodings, so make sure
  431. # its output is properly treated as utf8
  432. return decode_utf8(POSIX::strftime($format, localtime($time)));
  433. } #}}}
  434. sub beautify_url ($) { #{{{
  435. my $url=shift;
  436. $url =~ s!/index.$config{htmlext}$!/!;
  437. $url =~ s!^$!./!; # Browsers don't like empty links...
  438. return $url;
  439. } #}}}
  440. sub urlto ($$) { #{{{
  441. my $to=shift;
  442. my $from=shift;
  443. if (! length $to) {
  444. return beautify_url(baseurl($from));
  445. }
  446. if (! $destsources{$to}) {
  447. $to=htmlpage($to);
  448. }
  449. my $link = abs2rel($to, dirname(htmlpage($from)));
  450. return beautify_url($link);
  451. } #}}}
  452. sub htmllink ($$$;@) { #{{{
  453. my $lpage=shift; # the page doing the linking
  454. my $page=shift; # the page that will contain the link (different for inline)
  455. my $link=shift;
  456. my %opts=@_;
  457. my $bestlink;
  458. if (! $opts{forcesubpage}) {
  459. $bestlink=bestlink($lpage, $link);
  460. }
  461. else {
  462. $bestlink="$lpage/".lc($link);
  463. }
  464. my $linktext;
  465. if (defined $opts{linktext}) {
  466. $linktext=$opts{linktext};
  467. }
  468. else {
  469. $linktext=pagetitle(basename($link));
  470. }
  471. return "<span class=\"selflink\">$linktext</span>"
  472. if length $bestlink && $page eq $bestlink;
  473. if (! $destsources{$bestlink}) {
  474. $bestlink=htmlpage($bestlink);
  475. if (! $destsources{$bestlink}) {
  476. return $linktext unless length $config{cgiurl};
  477. return "<span class=\"createlink\"><a href=\"".
  478. cgiurl(
  479. do => "create",
  480. page => pagetitle(lc($link), 1),
  481. from => $lpage
  482. ).
  483. "\">?</a>$linktext</span>"
  484. }
  485. }
  486. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  487. $bestlink=beautify_url($bestlink);
  488. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  489. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  490. }
  491. if (defined $opts{anchor}) {
  492. $bestlink.="#".$opts{anchor};
  493. }
  494. my @attrs;
  495. if (defined $opts{rel}) {
  496. push @attrs, ' rel="'.$opts{rel}.'"';
  497. }
  498. if (defined $opts{class}) {
  499. push @attrs, ' class="'.$opts{class}.'"';
  500. }
  501. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  502. } #}}}
  503. sub htmlize ($$$) { #{{{
  504. my $page=shift;
  505. my $type=shift;
  506. my $content=shift;
  507. if (exists $hooks{htmlize}{$type}) {
  508. $content=$hooks{htmlize}{$type}{call}->(
  509. page => $page,
  510. content => $content,
  511. );
  512. }
  513. else {
  514. error("htmlization of $type not supported");
  515. }
  516. run_hooks(sanitize => sub {
  517. $content=shift->(
  518. page => $page,
  519. content => $content,
  520. );
  521. });
  522. return $content;
  523. } #}}}
  524. sub linkify ($$$) { #{{{
  525. my $lpage=shift; # the page containing the links
  526. my $page=shift; # the page the link will end up on (different for inline)
  527. my $content=shift;
  528. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  529. defined $2
  530. ? ( $1
  531. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  532. : htmllink($lpage, $page, linkpage($3),
  533. anchor => $4, linktext => pagetitle($2)))
  534. : ( $1
  535. ? "[[$3".($4 ? "#$4" : "")."]]"
  536. : htmllink($lpage, $page, linkpage($3),
  537. anchor => $4))
  538. }eg;
  539. return $content;
  540. } #}}}
  541. my %preprocessing;
  542. our $preprocess_preview=0;
  543. sub preprocess ($$$;$$) { #{{{
  544. my $page=shift; # the page the data comes from
  545. my $destpage=shift; # the page the data will appear in (different for inline)
  546. my $content=shift;
  547. my $scan=shift;
  548. my $preview=shift;
  549. # Using local because it needs to be set within any nested calls
  550. # of this function.
  551. local $preprocess_preview=$preview if defined $preview;
  552. my $handle=sub {
  553. my $escape=shift;
  554. my $command=shift;
  555. my $params=shift;
  556. if (length $escape) {
  557. return "[[$command $params]]";
  558. }
  559. elsif (exists $hooks{preprocess}{$command}) {
  560. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  561. # Note: preserve order of params, some plugins may
  562. # consider it significant.
  563. my @params;
  564. while ($params =~ m{
  565. (?:(\w+)=)? # 1: named parameter key?
  566. (?:
  567. """(.*?)""" # 2: triple-quoted value
  568. |
  569. "([^"]+)" # 3: single-quoted value
  570. |
  571. (\S+) # 4: unquoted value
  572. )
  573. (?:\s+|$) # delimiter to next param
  574. }sgx) {
  575. my $key=$1;
  576. my $val;
  577. if (defined $2) {
  578. $val=$2;
  579. $val=~s/\r\n/\n/mg;
  580. $val=~s/^\n+//g;
  581. $val=~s/\n+$//g;
  582. }
  583. elsif (defined $3) {
  584. $val=$3;
  585. }
  586. elsif (defined $4) {
  587. $val=$4;
  588. }
  589. if (defined $key) {
  590. push @params, $key, $val;
  591. }
  592. else {
  593. push @params, $val, '';
  594. }
  595. }
  596. if ($preprocessing{$page}++ > 3) {
  597. # Avoid loops of preprocessed pages preprocessing
  598. # other pages that preprocess them, etc.
  599. #translators: The first parameter is a
  600. #translators: preprocessor directive name,
  601. #translators: the second a page name, the
  602. #translators: third a number.
  603. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  604. $command, $page, $preprocessing{$page}).
  605. "]]";
  606. }
  607. my $ret=$hooks{preprocess}{$command}{call}->(
  608. @params,
  609. page => $page,
  610. destpage => $destpage,
  611. preview => $preprocess_preview,
  612. );
  613. $preprocessing{$page}--;
  614. return $ret;
  615. }
  616. else {
  617. return "[[$command $params]]";
  618. }
  619. };
  620. $content =~ s{
  621. (\\?) # 1: escape?
  622. \[\[ # directive open
  623. (\w+) # 2: command
  624. \s+
  625. ( # 3: the parameters..
  626. (?:
  627. (?:\w+=)? # named parameter key?
  628. (?:
  629. """.*?""" # triple-quoted value
  630. |
  631. "[^"]+" # single-quoted value
  632. |
  633. [^\s\]]+ # unquoted value
  634. )
  635. \s* # whitespace or end
  636. # of directive
  637. )
  638. *) # 0 or more parameters
  639. \]\] # directive closed
  640. }{$handle->($1, $2, $3)}sexg;
  641. return $content;
  642. } #}}}
  643. sub filter ($$$) { #{{{
  644. my $page=shift;
  645. my $destpage=shift;
  646. my $content=shift;
  647. run_hooks(filter => sub {
  648. $content=shift->(page => $page, destpage => $destpage,
  649. content => $content);
  650. });
  651. return $content;
  652. } #}}}
  653. sub indexlink () { #{{{
  654. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  655. } #}}}
  656. my $wikilock;
  657. sub lockwiki (;$) { #{{{
  658. my $wait=@_ ? shift : 1;
  659. # Take an exclusive lock on the wiki to prevent multiple concurrent
  660. # run issues. The lock will be dropped on program exit.
  661. if (! -d $config{wikistatedir}) {
  662. mkdir($config{wikistatedir});
  663. }
  664. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  665. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  666. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  667. if ($wait) {
  668. debug("wiki seems to be locked, waiting for lock");
  669. my $wait=600; # arbitrary, but don't hang forever to
  670. # prevent process pileup
  671. for (1..$wait) {
  672. return if flock($wikilock, 2 | 4);
  673. sleep 1;
  674. }
  675. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  676. }
  677. else {
  678. return 0;
  679. }
  680. }
  681. return 1;
  682. } #}}}
  683. sub unlockwiki () { #{{{
  684. return close($wikilock) if $wikilock;
  685. return;
  686. } #}}}
  687. my $commitlock;
  688. sub commit_hook_enabled () { #{{{
  689. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  690. error("cannot write to $config{wikistatedir}/commitlock: $!");
  691. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  692. close($commitlock) || error("failed closing commitlock: $!");
  693. return 0;
  694. }
  695. close($commitlock) || error("failed closing commitlock: $!");
  696. return 1;
  697. } #}}}
  698. sub disable_commit_hook () { #{{{
  699. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  700. error("cannot write to $config{wikistatedir}/commitlock: $!");
  701. if (! flock($commitlock, 2)) { # LOCK_EX
  702. error("failed to get commit lock");
  703. }
  704. return 1;
  705. } #}}}
  706. sub enable_commit_hook () { #{{{
  707. return close($commitlock) if $commitlock;
  708. return;
  709. } #}}}
  710. sub loadindex () { #{{{
  711. %oldrenderedfiles=%pagectime=();
  712. if (! $config{rebuild}) {
  713. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  714. %destsources=%renderedfiles=%pagecase=();
  715. }
  716. open (my $in, "<", "$config{wikistatedir}/index") || return;
  717. while (<$in>) {
  718. $_=possibly_foolish_untaint($_);
  719. chomp;
  720. my %items;
  721. $items{link}=[];
  722. $items{dest}=[];
  723. foreach my $i (split(/ /, $_)) {
  724. my ($item, $val)=split(/=/, $i, 2);
  725. push @{$items{$item}}, decode_entities($val);
  726. }
  727. next unless exists $items{src}; # skip bad lines for now
  728. my $page=pagename($items{src}[0]);
  729. if (! $config{rebuild}) {
  730. $pagesources{$page}=$items{src}[0];
  731. $pagemtime{$page}=$items{mtime}[0];
  732. $oldlinks{$page}=[@{$items{link}}];
  733. $links{$page}=[@{$items{link}}];
  734. $depends{$page}=$items{depends}[0] if exists $items{depends};
  735. $destsources{$_}=$page foreach @{$items{dest}};
  736. $renderedfiles{$page}=[@{$items{dest}}];
  737. $pagecase{lc $page}=$page;
  738. }
  739. $oldrenderedfiles{$page}=[@{$items{dest}}];
  740. $pagectime{$page}=$items{ctime}[0];
  741. }
  742. return close($in);
  743. } #}}}
  744. sub saveindex () { #{{{
  745. run_hooks(savestate => sub { shift->() });
  746. if (! -d $config{wikistatedir}) {
  747. mkdir($config{wikistatedir});
  748. }
  749. my $newfile="$config{wikistatedir}/index.new";
  750. my $cleanup = sub { unlink($newfile) };
  751. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  752. foreach my $page (keys %pagemtime) {
  753. next unless $pagemtime{$page};
  754. my $line="mtime=$pagemtime{$page} ".
  755. "ctime=$pagectime{$page} ".
  756. "src=$pagesources{$page}";
  757. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  758. my %count;
  759. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  760. if (exists $depends{$page}) {
  761. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  762. }
  763. print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  764. }
  765. close $out || error("failed saving to $newfile: $!", $cleanup);
  766. rename($newfile, "$config{wikistatedir}/index") ||
  767. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  768. return 1;
  769. } #}}}
  770. sub template_file ($) { #{{{
  771. my $template=shift;
  772. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  773. return "$dir/$template" if -e "$dir/$template";
  774. }
  775. return;
  776. } #}}}
  777. sub template_params (@) { #{{{
  778. my $filename=template_file(shift);
  779. if (! defined $filename) {
  780. return if wantarray;
  781. return "";
  782. }
  783. my @ret=(
  784. filter => sub {
  785. my $text_ref = shift;
  786. ${$text_ref} = decode_utf8(${$text_ref});
  787. },
  788. filename => $filename,
  789. loop_context_vars => 1,
  790. die_on_bad_params => 0,
  791. @_
  792. );
  793. return wantarray ? @ret : {@ret};
  794. } #}}}
  795. sub template ($;@) { #{{{
  796. require HTML::Template;
  797. return HTML::Template->new(template_params(@_));
  798. } #}}}
  799. sub misctemplate ($$;@) { #{{{
  800. my $title=shift;
  801. my $pagebody=shift;
  802. my $template=template("misc.tmpl");
  803. $template->param(
  804. title => $title,
  805. indexlink => indexlink(),
  806. wikiname => $config{wikiname},
  807. pagebody => $pagebody,
  808. baseurl => baseurl(),
  809. @_,
  810. );
  811. run_hooks(pagetemplate => sub {
  812. shift->(page => "", destpage => "", template => $template);
  813. });
  814. return $template->output;
  815. }#}}}
  816. sub hook (@) { # {{{
  817. my %param=@_;
  818. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  819. error 'hook requires type, call, and id parameters';
  820. }
  821. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  822. $hooks{$param{type}}{$param{id}}=\%param;
  823. return 1;
  824. } # }}}
  825. sub run_hooks ($$) { # {{{
  826. # Calls the given sub for each hook of the given type,
  827. # passing it the hook function to call.
  828. my $type=shift;
  829. my $sub=shift;
  830. if (exists $hooks{$type}) {
  831. my @deferred;
  832. foreach my $id (keys %{$hooks{$type}}) {
  833. if ($hooks{$type}{$id}{last}) {
  834. push @deferred, $id;
  835. next;
  836. }
  837. $sub->($hooks{$type}{$id}{call});
  838. }
  839. foreach my $id (@deferred) {
  840. $sub->($hooks{$type}{$id}{call});
  841. }
  842. }
  843. return 1;
  844. } #}}}
  845. sub globlist_to_pagespec ($) { #{{{
  846. my @globlist=split(' ', shift);
  847. my (@spec, @skip);
  848. foreach my $glob (@globlist) {
  849. if ($glob=~/^!(.*)/) {
  850. push @skip, $glob;
  851. }
  852. else {
  853. push @spec, $glob;
  854. }
  855. }
  856. my $spec=join(' or ', @spec);
  857. if (@skip) {
  858. my $skip=join(' and ', @skip);
  859. if (length $spec) {
  860. $spec="$skip and ($spec)";
  861. }
  862. else {
  863. $spec=$skip;
  864. }
  865. }
  866. return $spec;
  867. } #}}}
  868. sub is_globlist ($) { #{{{
  869. my $s=shift;
  870. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  871. } #}}}
  872. sub safequote ($) { #{{{
  873. my $s=shift;
  874. $s=~s/[{}]//g;
  875. return "q{$s}";
  876. } #}}}
  877. sub add_depends ($$) { #{{{
  878. my $page=shift;
  879. my $pagespec=shift;
  880. if (! exists $depends{$page}) {
  881. $depends{$page}=$pagespec;
  882. }
  883. else {
  884. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  885. }
  886. return 1;
  887. } # }}}
  888. sub file_pruned ($$) { #{{{
  889. require File::Spec;
  890. my $file=File::Spec->canonpath(shift);
  891. my $base=File::Spec->canonpath(shift);
  892. $file =~ s#^\Q$base\E/*##;
  893. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  894. return $file =~ m/$regexp/;
  895. } #}}}
  896. sub gettext { #{{{
  897. # Only use gettext in the rare cases it's needed.
  898. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  899. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  900. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  901. if (! $gettext_obj) {
  902. $gettext_obj=eval q{
  903. use Locale::gettext q{textdomain};
  904. Locale::gettext->domain('ikiwiki')
  905. };
  906. if ($@) {
  907. print STDERR "$@";
  908. $gettext_obj=undef;
  909. return shift;
  910. }
  911. }
  912. return $gettext_obj->get(shift);
  913. }
  914. else {
  915. return shift;
  916. }
  917. } #}}}
  918. sub pagespec_merge ($$) { #{{{
  919. my $a=shift;
  920. my $b=shift;
  921. return $a if $a eq $b;
  922. # Support for old-style GlobLists.
  923. if (is_globlist($a)) {
  924. $a=globlist_to_pagespec($a);
  925. }
  926. if (is_globlist($b)) {
  927. $b=globlist_to_pagespec($b);
  928. }
  929. return "($a) or ($b)";
  930. } #}}}
  931. sub pagespec_translate ($) { #{{{
  932. # This assumes that $page is in scope in the function
  933. # that evalulates the translated pagespec code.
  934. my $spec=shift;
  935. # Support for old-style GlobLists.
  936. if (is_globlist($spec)) {
  937. $spec=globlist_to_pagespec($spec);
  938. }
  939. # Convert spec to perl code.
  940. my $code="";
  941. while ($spec=~m{
  942. \s* # ignore whitespace
  943. ( # 1: match a single word
  944. \! # !
  945. |
  946. \( # (
  947. |
  948. \) # )
  949. |
  950. \w+\([^\)]*\) # command(params)
  951. |
  952. [^\s()]+ # any other text
  953. )
  954. \s* # ignore whitespace
  955. }igx) {
  956. my $word=$1;
  957. if (lc $word eq 'and') {
  958. $code.=' &&';
  959. }
  960. elsif (lc $word eq 'or') {
  961. $code.=' ||';
  962. }
  963. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  964. $code.=' '.$word;
  965. }
  966. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  967. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  968. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
  969. }
  970. else {
  971. $code.=' 0';
  972. }
  973. }
  974. else {
  975. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
  976. }
  977. }
  978. return $code;
  979. } #}}}
  980. sub pagespec_match ($$;@) { #{{{
  981. my $page=shift;
  982. my $spec=shift;
  983. my @params=@_;
  984. # Backwards compatability with old calling convention.
  985. if (@params == 1) {
  986. unshift @params, 'location';
  987. }
  988. my $ret=eval pagespec_translate($spec);
  989. return IkiWiki::FailReason->new('syntax error') if $@;
  990. return $ret;
  991. } #}}}
  992. package IkiWiki::FailReason;
  993. use overload ( #{{{
  994. '""' => sub { ${$_[0]} },
  995. '0+' => sub { 0 },
  996. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  997. fallback => 1,
  998. ); #}}}
  999. sub new { #{{{
  1000. return bless \$_[1], $_[0];
  1001. } #}}}
  1002. package IkiWiki::SuccessReason;
  1003. use overload ( #{{{
  1004. '""' => sub { ${$_[0]} },
  1005. '0+' => sub { 1 },
  1006. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1007. fallback => 1,
  1008. ); #}}}
  1009. sub new { #{{{
  1010. return bless \$_[1], $_[0];
  1011. }; #}}}
  1012. package IkiWiki::PageSpec;
  1013. sub match_glob ($$;@) { #{{{
  1014. my $page=shift;
  1015. my $glob=shift;
  1016. my %params=@_;
  1017. my $from=exists $params{location} ? $params{location} : '';
  1018. # relative matching
  1019. if ($glob =~ m!^\./!) {
  1020. $from=~s#/?[^/]+$##;
  1021. $glob=~s#^\./##;
  1022. $glob="$from/$glob" if length $from;
  1023. }
  1024. # turn glob into safe regexp
  1025. $glob=quotemeta($glob);
  1026. $glob=~s/\\\*/.*/g;
  1027. $glob=~s/\\\?/./g;
  1028. if ($page=~/^$glob$/i) {
  1029. return IkiWiki::SuccessReason->new("$glob matches $page");
  1030. }
  1031. else {
  1032. return IkiWiki::FailReason->new("$glob does not match $page");
  1033. }
  1034. } #}}}
  1035. sub match_link ($$;@) { #{{{
  1036. my $page=shift;
  1037. my $link=lc(shift);
  1038. my %params=@_;
  1039. my $from=exists $params{location} ? $params{location} : '';
  1040. # relative matching
  1041. if ($link =~ m!^\.! && defined $from) {
  1042. $from=~s#/?[^/]+$##;
  1043. $link=~s#^\./##;
  1044. $link="$from/$link" if length $from;
  1045. }
  1046. my $links = $IkiWiki::links{$page};
  1047. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1048. my $bestlink = IkiWiki::bestlink($from, $link);
  1049. foreach my $p (@{$links}) {
  1050. if (length $bestlink) {
  1051. return IkiWiki::SuccessReason->new("$page links to $link")
  1052. if $bestlink eq IkiWiki::bestlink($page, $p);
  1053. }
  1054. else {
  1055. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1056. if match_glob($p, $link, %params);
  1057. }
  1058. }
  1059. return IkiWiki::FailReason->new("$page does not link to $link");
  1060. } #}}}
  1061. sub match_backlink ($$;@) { #{{{
  1062. return match_link($_[1], $_[0], @_);
  1063. } #}}}
  1064. sub match_created_before ($$;@) { #{{{
  1065. my $page=shift;
  1066. my $testpage=shift;
  1067. if (exists $IkiWiki::pagectime{$testpage}) {
  1068. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1069. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1070. }
  1071. else {
  1072. return IkiWiki::FailReason->new("$page not created before $testpage");
  1073. }
  1074. }
  1075. else {
  1076. return IkiWiki::FailReason->new("$testpage has no ctime");
  1077. }
  1078. } #}}}
  1079. sub match_created_after ($$;@) { #{{{
  1080. my $page=shift;
  1081. my $testpage=shift;
  1082. if (exists $IkiWiki::pagectime{$testpage}) {
  1083. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1084. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1085. }
  1086. else {
  1087. return IkiWiki::FailReason->new("$page not created after $testpage");
  1088. }
  1089. }
  1090. else {
  1091. return IkiWiki::FailReason->new("$testpage has no ctime");
  1092. }
  1093. } #}}}
  1094. sub match_creation_day ($$;@) { #{{{
  1095. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1096. return IkiWiki::SuccessReason->new('creation_day matched');
  1097. }
  1098. else {
  1099. return IkiWiki::FailReason->new('creation_day did not match');
  1100. }
  1101. } #}}}
  1102. sub match_creation_month ($$;@) { #{{{
  1103. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1104. return IkiWiki::SuccessReason->new('creation_month matched');
  1105. }
  1106. else {
  1107. return IkiWiki::FailReason->new('creation_month did not match');
  1108. }
  1109. } #}}}
  1110. sub match_creation_year ($$;@) { #{{{
  1111. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1112. return IkiWiki::SuccessReason->new('creation_year matched');
  1113. }
  1114. else {
  1115. return IkiWiki::FailReason->new('creation_year did not match');
  1116. }
  1117. } #}}}
  1118. sub match_user ($$;@) { #{{{
  1119. shift;
  1120. my $user=shift;
  1121. my %params=@_;
  1122. return IkiWiki::FailReason->new('cannot match user')
  1123. unless exists $params{user};
  1124. if ($user eq $params{user}) {
  1125. return IkiWiki::SuccessReason->new("user is $user")
  1126. }
  1127. else {
  1128. return IkiWiki::FailReason->new("user is not $user");
  1129. }
  1130. } #}}}
  1131. 1