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