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