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