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