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