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