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