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