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