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