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