summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 18a518f3f57ba06c7fdb4942e90cd13af4a1d882 (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 (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  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) if $wikilock;
  665. return;
  666. } #}}}
  667. my $commitlock;
  668. sub commit_hook_enabled () { #{{{
  669. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  670. error("cannot write to $config{wikistatedir}/commitlock: $!");
  671. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  672. close($commitlock) || error("failed closing commitlock: $!");
  673. return 0;
  674. }
  675. close($commitlock) || error("failed closing commitlock: $!");
  676. return 1;
  677. } #}}}
  678. sub disable_commit_hook () { #{{{
  679. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  680. error("cannot write to $config{wikistatedir}/commitlock: $!");
  681. if (! flock($commitlock, 2)) { # LOCK_EX
  682. error("failed to get commit lock");
  683. }
  684. return 1;
  685. } #}}}
  686. sub enable_commit_hook () { #{{{
  687. return close($commitlock) if $commitlock;
  688. return;
  689. } #}}}
  690. sub loadindex () { #{{{
  691. open (my $in, "<", "$config{wikistatedir}/index") || return;
  692. while (<$in>) {
  693. $_=possibly_foolish_untaint($_);
  694. chomp;
  695. my %items;
  696. $items{link}=[];
  697. $items{dest}=[];
  698. foreach my $i (split(/ /, $_)) {
  699. my ($item, $val)=split(/=/, $i, 2);
  700. push @{$items{$item}}, decode_entities($val);
  701. }
  702. next unless exists $items{src}; # skip bad lines for now
  703. my $page=pagename($items{src}[0]);
  704. if (! $config{rebuild}) {
  705. $pagesources{$page}=$items{src}[0];
  706. $pagemtime{$page}=$items{mtime}[0];
  707. $oldlinks{$page}=[@{$items{link}}];
  708. $links{$page}=[@{$items{link}}];
  709. $depends{$page}=$items{depends}[0] if exists $items{depends};
  710. $destsources{$_}=$page foreach @{$items{dest}};
  711. $renderedfiles{$page}=[@{$items{dest}}];
  712. $pagecase{lc $page}=$page;
  713. }
  714. $oldrenderedfiles{$page}=[@{$items{dest}}];
  715. $pagectime{$page}=$items{ctime}[0];
  716. }
  717. return close($in);
  718. } #}}}
  719. sub saveindex () { #{{{
  720. run_hooks(savestate => sub { shift->() });
  721. if (! -d $config{wikistatedir}) {
  722. mkdir($config{wikistatedir});
  723. }
  724. my $newfile="$config{wikistatedir}/index.new";
  725. my $cleanup = sub { unlink($newfile) };
  726. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  727. foreach my $page (keys %pagemtime) {
  728. next unless $pagemtime{$page};
  729. my $line="mtime=$pagemtime{$page} ".
  730. "ctime=$pagectime{$page} ".
  731. "src=$pagesources{$page}";
  732. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  733. my %count;
  734. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  735. if (exists $depends{$page}) {
  736. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  737. }
  738. print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  739. }
  740. close $out || error("failed saving to $newfile: $!", $cleanup);
  741. rename($newfile, "$config{wikistatedir}/index") ||
  742. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  743. return 1;
  744. } #}}}
  745. sub template_file ($) { #{{{
  746. my $template=shift;
  747. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  748. return "$dir/$template" if -e "$dir/$template";
  749. }
  750. return;
  751. } #}}}
  752. sub template_params (@) { #{{{
  753. my $filename=template_file(shift);
  754. if (! defined $filename) {
  755. return if wantarray;
  756. return "";
  757. }
  758. my @ret=(
  759. filter => sub {
  760. my $text_ref = shift;
  761. ${$text_ref} = Encode::decode_utf8(${$text_ref});
  762. },
  763. filename => $filename,
  764. loop_context_vars => 1,
  765. die_on_bad_params => 0,
  766. @_
  767. );
  768. return wantarray ? @ret : {@ret};
  769. } #}}}
  770. sub template ($;@) { #{{{
  771. require HTML::Template;
  772. return HTML::Template->new(template_params(@_));
  773. } #}}}
  774. sub misctemplate ($$;@) { #{{{
  775. my $title=shift;
  776. my $pagebody=shift;
  777. my $template=template("misc.tmpl");
  778. $template->param(
  779. title => $title,
  780. indexlink => indexlink(),
  781. wikiname => $config{wikiname},
  782. pagebody => $pagebody,
  783. baseurl => baseurl(),
  784. @_,
  785. );
  786. run_hooks(pagetemplate => sub {
  787. shift->(page => "", destpage => "", template => $template);
  788. });
  789. return $template->output;
  790. }#}}}
  791. sub hook (@) { # {{{
  792. my %param=@_;
  793. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  794. error 'hook requires type, call, and id parameters';
  795. }
  796. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  797. $hooks{$param{type}}{$param{id}}=\%param;
  798. return 1;
  799. } # }}}
  800. sub run_hooks ($$) { # {{{
  801. # Calls the given sub for each hook of the given type,
  802. # passing it the hook function to call.
  803. my $type=shift;
  804. my $sub=shift;
  805. if (exists $hooks{$type}) {
  806. my @deferred;
  807. foreach my $id (keys %{$hooks{$type}}) {
  808. if ($hooks{$type}{$id}{last}) {
  809. push @deferred, $id;
  810. next;
  811. }
  812. $sub->($hooks{$type}{$id}{call});
  813. }
  814. foreach my $id (@deferred) {
  815. $sub->($hooks{$type}{$id}{call});
  816. }
  817. }
  818. return 1;
  819. } #}}}
  820. sub globlist_to_pagespec ($) { #{{{
  821. my @globlist=split(' ', shift);
  822. my (@spec, @skip);
  823. foreach my $glob (@globlist) {
  824. if ($glob=~/^!(.*)/) {
  825. push @skip, $glob;
  826. }
  827. else {
  828. push @spec, $glob;
  829. }
  830. }
  831. my $spec=join(' or ', @spec);
  832. if (@skip) {
  833. my $skip=join(' and ', @skip);
  834. if (length $spec) {
  835. $spec="$skip and ($spec)";
  836. }
  837. else {
  838. $spec=$skip;
  839. }
  840. }
  841. return $spec;
  842. } #}}}
  843. sub is_globlist ($) { #{{{
  844. my $s=shift;
  845. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  846. } #}}}
  847. sub safequote ($) { #{{{
  848. my $s=shift;
  849. $s=~s/[{}]//g;
  850. return "q{$s}";
  851. } #}}}
  852. sub add_depends ($$) { #{{{
  853. my $page=shift;
  854. my $pagespec=shift;
  855. if (! exists $depends{$page}) {
  856. $depends{$page}=$pagespec;
  857. }
  858. else {
  859. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  860. }
  861. return 1;
  862. } # }}}
  863. sub file_pruned ($$) { #{{{
  864. require File::Spec;
  865. my $file=File::Spec->canonpath(shift);
  866. my $base=File::Spec->canonpath(shift);
  867. $file =~ s#^\Q$base\E/*##;
  868. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  869. return $file =~ m/$regexp/;
  870. } #}}}
  871. sub gettext { #{{{
  872. # Only use gettext in the rare cases it's needed.
  873. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  874. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  875. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  876. if (! $gettext_obj) {
  877. $gettext_obj=eval q{
  878. use Locale::gettext q{textdomain};
  879. Locale::gettext->domain('ikiwiki')
  880. };
  881. if ($@) {
  882. print STDERR "$@";
  883. $gettext_obj=undef;
  884. return shift;
  885. }
  886. }
  887. return $gettext_obj->get(shift);
  888. }
  889. else {
  890. return shift;
  891. }
  892. } #}}}
  893. sub pagespec_merge ($$) { #{{{
  894. my $a=shift;
  895. my $b=shift;
  896. return $a if $a eq $b;
  897. # Support for old-style GlobLists.
  898. if (is_globlist($a)) {
  899. $a=globlist_to_pagespec($a);
  900. }
  901. if (is_globlist($b)) {
  902. $b=globlist_to_pagespec($b);
  903. }
  904. return "($a) or ($b)";
  905. } #}}}
  906. sub pagespec_translate ($) { #{{{
  907. # This assumes that $page is in scope in the function
  908. # that evalulates the translated pagespec code.
  909. my $spec=shift;
  910. # Support for old-style GlobLists.
  911. if (is_globlist($spec)) {
  912. $spec=globlist_to_pagespec($spec);
  913. }
  914. # Convert spec to perl code.
  915. my $code="";
  916. while ($spec=~m{
  917. \s* # ignore whitespace
  918. ( # 1: match a single word
  919. \! # !
  920. |
  921. \( # (
  922. |
  923. \) # )
  924. |
  925. \w+\([^\)]*\) # command(params)
  926. |
  927. [^\s()]+ # any other text
  928. )
  929. \s* # ignore whitespace
  930. }igx) {
  931. my $word=$1;
  932. if (lc $word eq 'and') {
  933. $code.=' &&';
  934. }
  935. elsif (lc $word eq 'or') {
  936. $code.=' ||';
  937. }
  938. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  939. $code.=' '.$word;
  940. }
  941. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  942. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  943. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
  944. }
  945. else {
  946. $code.=' 0';
  947. }
  948. }
  949. else {
  950. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
  951. }
  952. }
  953. return $code;
  954. } #}}}
  955. sub pagespec_match ($$;@) { #{{{
  956. my $page=shift;
  957. my $spec=shift;
  958. my @params=@_;
  959. # Backwards compatability with old calling convention.
  960. if (@params == 1) {
  961. unshift @params, 'location';
  962. }
  963. my $ret=eval pagespec_translate($spec);
  964. return IkiWiki::FailReason->new('syntax error') if $@;
  965. return $ret;
  966. } #}}}
  967. package IkiWiki::FailReason;
  968. use overload ( #{{{
  969. '""' => sub { ${$_[0]} },
  970. '0+' => sub { 0 },
  971. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  972. fallback => 1,
  973. ); #}}}
  974. sub new { #{{{
  975. return bless \$_[1], $_[0];
  976. } #}}}
  977. package IkiWiki::SuccessReason;
  978. use overload ( #{{{
  979. '""' => sub { ${$_[0]} },
  980. '0+' => sub { 1 },
  981. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  982. fallback => 1,
  983. ); #}}}
  984. sub new { #{{{
  985. return bless \$_[1], $_[0];
  986. }; #}}}
  987. package IkiWiki::PageSpec;
  988. sub match_glob ($$;@) { #{{{
  989. my $page=shift;
  990. my $glob=shift;
  991. my %params=@_;
  992. my $from=exists $params{location} ? $params{location} : '';
  993. # relative matching
  994. if ($glob =~ m!^\./!) {
  995. $from=~s#/?[^/]+$##;
  996. $glob=~s#^\./##;
  997. $glob="$from/$glob" if length $from;
  998. }
  999. # turn glob into safe regexp
  1000. $glob=quotemeta($glob);
  1001. $glob=~s/\\\*/.*/g;
  1002. $glob=~s/\\\?/./g;
  1003. if ($page=~/^$glob$/i) {
  1004. return IkiWiki::SuccessReason->new("$glob matches $page");
  1005. }
  1006. else {
  1007. return IkiWiki::FailReason->new("$glob does not match $page");
  1008. }
  1009. } #}}}
  1010. sub match_link ($$;@) { #{{{
  1011. my $page=shift;
  1012. my $link=lc(shift);
  1013. my %params=@_;
  1014. my $from=exists $params{location} ? $params{location} : '';
  1015. # relative matching
  1016. if ($link =~ m!^\.! && defined $from) {
  1017. $from=~s#/?[^/]+$##;
  1018. $link=~s#^\./##;
  1019. $link="$from/$link" if length $from;
  1020. }
  1021. my $links = $IkiWiki::links{$page};
  1022. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1023. my $bestlink = IkiWiki::bestlink($from, $link);
  1024. foreach my $p (@{$links}) {
  1025. if (length $bestlink) {
  1026. return IkiWiki::SuccessReason->new("$page links to $link")
  1027. if $bestlink eq IkiWiki::bestlink($page, $p);
  1028. }
  1029. else {
  1030. return IkiWiki::SuccessReason->new("$page links to page matching $link")
  1031. if match_glob($p, $link, %params);
  1032. }
  1033. }
  1034. return IkiWiki::FailReason->new("$page does not link to $link");
  1035. } #}}}
  1036. sub match_backlink ($$;@) { #{{{
  1037. return match_link($_[1], $_[0], @_);
  1038. } #}}}
  1039. sub match_created_before ($$;@) { #{{{
  1040. my $page=shift;
  1041. my $testpage=shift;
  1042. if (exists $IkiWiki::pagectime{$testpage}) {
  1043. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1044. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1045. }
  1046. else {
  1047. return IkiWiki::FailReason->new("$page not created before $testpage");
  1048. }
  1049. }
  1050. else {
  1051. return IkiWiki::FailReason->new("$testpage has no ctime");
  1052. }
  1053. } #}}}
  1054. sub match_created_after ($$;@) { #{{{
  1055. my $page=shift;
  1056. my $testpage=shift;
  1057. if (exists $IkiWiki::pagectime{$testpage}) {
  1058. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1059. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1060. }
  1061. else {
  1062. return IkiWiki::FailReason->new("$page not created after $testpage");
  1063. }
  1064. }
  1065. else {
  1066. return IkiWiki::FailReason->new("$testpage has no ctime");
  1067. }
  1068. } #}}}
  1069. sub match_creation_day ($$;@) { #{{{
  1070. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1071. return IkiWiki::SuccessReason->new('creation_day matched');
  1072. }
  1073. else {
  1074. return IkiWiki::FailReason->new('creation_day did not match');
  1075. }
  1076. } #}}}
  1077. sub match_creation_month ($$;@) { #{{{
  1078. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1079. return IkiWiki::SuccessReason->new('creation_month matched');
  1080. }
  1081. else {
  1082. return IkiWiki::FailReason->new('creation_month did not match');
  1083. }
  1084. } #}}}
  1085. sub match_creation_year ($$;@) { #{{{
  1086. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1087. return IkiWiki::SuccessReason->new('creation_year matched');
  1088. }
  1089. else {
  1090. return IkiWiki::FailReason->new('creation_year did not match');
  1091. }
  1092. } #}}}
  1093. sub match_user ($$;@) { #{{{
  1094. shift;
  1095. my $user=shift;
  1096. my %params=@_;
  1097. return IkiWiki::FailReason->new('cannot match user')
  1098. unless exists $params{user};
  1099. if ($user eq $params{user}) {
  1100. return IkiWiki::SuccessReason->new("user is $user")
  1101. }
  1102. else {
  1103. return IkiWiki::FailReason->new("user is not $user");
  1104. }
  1105. } #}}}
  1106. 1