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