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