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