summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: a6bfddab06f8b406fcb4bde84f745d5bc667c357 (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 open qw{:utf8 :std};
  9. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  10. %renderedfiles %oldrenderedfiles %pagesources %destsources
  11. %depends %hooks %forcerebuild $gettext_obj};
  12. use Exporter q{import};
  13. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  14. bestlink htmllink readfile writefile pagetype srcfile pagename
  15. displaytime will_render gettext urlto targetpage
  16. %config %links %renderedfiles %pagesources);
  17. our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
  18. our $version="1.45";my $installdir="/usr";
  19. # Optimisation.
  20. use Memoize;
  21. memoize("abs2rel");
  22. memoize("pagespec_translate");
  23. memoize("file_pruned");
  24. sub defaultconfig () { #{{{
  25. wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
  26. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  27. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
  28. wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
  29. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  30. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  31. verbose => 0,
  32. syslog => 0,
  33. wikiname => "wiki",
  34. default_pageext => "mdwn",
  35. cgi => 0,
  36. post_commit => 0,
  37. rcs => '',
  38. notify => 0,
  39. url => '',
  40. cgiurl => '',
  41. historyurl => '',
  42. diffurl => '',
  43. rss => 0,
  44. atom => 0,
  45. discussion => 1,
  46. rebuild => 0,
  47. refresh => 0,
  48. getctime => 0,
  49. w3mmode => 0,
  50. wrapper => undef,
  51. wrappermode => undef,
  52. svnrepo => undef,
  53. svnpath => "trunk",
  54. gitorigin_branch => "origin",
  55. gitmaster_branch => "master",
  56. srcdir => undef,
  57. destdir => undef,
  58. pingurl => [],
  59. templatedir => "$installdir/share/ikiwiki/templates",
  60. underlaydir => "$installdir/share/ikiwiki/basewiki",
  61. setup => undef,
  62. adminuser => undef,
  63. adminemail => undef,
  64. plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
  65. lockedit conditional}],
  66. timeformat => '%c',
  67. locale => undef,
  68. sslcookie => 0,
  69. httpauth => 0,
  70. userdir => "",
  71. usedirs => 0,
  72. numbacklinks => 10,
  73. } #}}}
  74. sub checkconfig () { #{{{
  75. # locale stuff; avoid LC_ALL since it overrides everything
  76. if (defined $ENV{LC_ALL}) {
  77. $ENV{LANG} = $ENV{LC_ALL};
  78. delete $ENV{LC_ALL};
  79. }
  80. if (defined $config{locale}) {
  81. eval q{use POSIX};
  82. error($@) if $@;
  83. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  84. $ENV{LANG}=$config{locale};
  85. $gettext_obj=undef;
  86. }
  87. }
  88. if ($config{w3mmode}) {
  89. eval q{use Cwd q{abs_path}};
  90. error($@) if $@;
  91. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  92. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  93. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  94. unless $config{cgiurl} =~ m!file:///!;
  95. $config{url}="file://".$config{destdir};
  96. }
  97. if ($config{cgi} && ! length $config{url}) {
  98. error(gettext("Must specify url to wiki with --url when using --cgi"));
  99. }
  100. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  101. unless exists $config{wikistatedir};
  102. if ($config{rcs}) {
  103. eval qq{require IkiWiki::Rcs::$config{rcs}};
  104. if ($@) {
  105. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  106. }
  107. }
  108. else {
  109. require IkiWiki::Rcs::Stub;
  110. }
  111. run_hooks(checkconfig => sub { shift->() });
  112. } #}}}
  113. sub loadplugins () { #{{{
  114. loadplugin($_) foreach @{$config{plugin}};
  115. run_hooks(getopt => sub { shift->() });
  116. if (grep /^-/, @ARGV) {
  117. print STDERR "Unknown option: $_\n"
  118. foreach grep /^-/, @ARGV;
  119. usage();
  120. }
  121. } #}}}
  122. sub loadplugin ($) { #{{{
  123. my $plugin=shift;
  124. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  125. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  126. eval qq{use $mod};
  127. if ($@) {
  128. error("Failed to load plugin $mod: $@");
  129. }
  130. } #}}}
  131. sub error ($;$) { #{{{
  132. my $message=shift;
  133. my $cleaner=shift;
  134. if ($config{cgi}) {
  135. print "Content-type: text/html\n\n";
  136. print misctemplate(gettext("Error"),
  137. "<p>".gettext("Error").": $message</p>");
  138. }
  139. log_message('err' => $message) if $config{syslog};
  140. if (defined $cleaner) {
  141. $cleaner->();
  142. }
  143. die $message."\n";
  144. } #}}}
  145. sub debug ($) { #{{{
  146. return unless $config{verbose};
  147. log_message(debug => @_);
  148. } #}}}
  149. my $log_open=0;
  150. sub log_message ($$) { #{{{
  151. my $type=shift;
  152. if ($config{syslog}) {
  153. require Sys::Syslog;
  154. unless ($log_open) {
  155. Sys::Syslog::setlogsock('unix');
  156. Sys::Syslog::openlog('ikiwiki', '', 'user');
  157. $log_open=1;
  158. }
  159. eval {
  160. Sys::Syslog::syslog($type, "%s", join(" ", @_));
  161. };
  162. }
  163. elsif (! $config{cgi}) {
  164. print "@_\n";
  165. }
  166. else {
  167. print STDERR "@_\n";
  168. }
  169. } #}}}
  170. sub possibly_foolish_untaint ($) { #{{{
  171. my $tainted=shift;
  172. my ($untainted)=$tainted=~/(.*)/;
  173. return $untainted;
  174. } #}}}
  175. sub basename ($) { #{{{
  176. my $file=shift;
  177. $file=~s!.*/+!!;
  178. return $file;
  179. } #}}}
  180. sub dirname ($) { #{{{
  181. my $file=shift;
  182. $file=~s!/*[^/]+$!!;
  183. return $file;
  184. } #}}}
  185. sub pagetype ($) { #{{{
  186. my $page=shift;
  187. if ($page =~ /\.([^.]+)$/) {
  188. return $1 if exists $hooks{htmlize}{$1};
  189. }
  190. return undef;
  191. } #}}}
  192. sub pagename ($) { #{{{
  193. my $file=shift;
  194. my $type=pagetype($file);
  195. my $page=$file;
  196. $page=~s/\Q.$type\E*$// if defined $type;
  197. return $page;
  198. } #}}}
  199. sub targetpage ($$) { #{{{
  200. my $page=shift;
  201. my $ext=shift;
  202. if (! $config{usedirs} || $page =~ /^index$/ ) {
  203. return $page.".".$ext;
  204. } else {
  205. return $page."/index.".$ext;
  206. }
  207. } #}}}
  208. sub htmlpage ($) { #{{{
  209. my $page=shift;
  210. return targetpage($page, "html");
  211. } #}}}
  212. sub srcfile ($) { #{{{
  213. my $file=shift;
  214. return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
  215. return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
  216. error("internal error: $file cannot be found");
  217. } #}}}
  218. sub readfile ($;$$) { #{{{
  219. my $file=shift;
  220. my $binary=shift;
  221. my $wantfd=shift;
  222. if (-l $file) {
  223. error("cannot read a symlink ($file)");
  224. }
  225. local $/=undef;
  226. open (IN, $file) || error("failed to read $file: $!");
  227. binmode(IN) if ($binary);
  228. return \*IN if $wantfd;
  229. my $ret=<IN>;
  230. close IN || error("failed to read $file: $!");
  231. return $ret;
  232. } #}}}
  233. sub writefile ($$$;$$) { #{{{
  234. my $file=shift; # can include subdirs
  235. my $destdir=shift; # directory to put file in
  236. my $content=shift;
  237. my $binary=shift;
  238. my $writer=shift;
  239. my $test=$file;
  240. while (length $test) {
  241. if (-l "$destdir/$test") {
  242. error("cannot write to a symlink ($test)");
  243. }
  244. $test=dirname($test);
  245. }
  246. my $newfile="$destdir/$file.ikiwiki-new";
  247. if (-l $newfile) {
  248. error("cannot write to a symlink ($newfile)");
  249. }
  250. my $dir=dirname($newfile);
  251. if (! -d $dir) {
  252. my $d="";
  253. foreach my $s (split(m!/+!, $dir)) {
  254. $d.="$s/";
  255. if (! -d $d) {
  256. mkdir($d) || error("failed to create directory $d: $!");
  257. }
  258. }
  259. }
  260. my $cleanup = sub { unlink($newfile) };
  261. open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
  262. binmode(OUT) if ($binary);
  263. if ($writer) {
  264. $writer->(\*OUT, $cleanup);
  265. }
  266. else {
  267. print OUT $content or error("failed writing to $newfile: $!", $cleanup);
  268. }
  269. close OUT || error("failed saving $newfile: $!", $cleanup);
  270. rename($newfile, "$destdir/$file") ||
  271. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  272. } #}}}
  273. my %cleared;
  274. sub will_render ($$;$) { #{{{
  275. my $page=shift;
  276. my $dest=shift;
  277. my $clear=shift;
  278. # Important security check.
  279. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  280. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  281. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  282. }
  283. if (! $clear || $cleared{$page}) {
  284. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  285. }
  286. else {
  287. foreach my $old (@{$renderedfiles{$page}}) {
  288. delete $destsources{$old};
  289. }
  290. $renderedfiles{$page}=[$dest];
  291. $cleared{$page}=1;
  292. }
  293. $destsources{$dest}=$page;
  294. } #}}}
  295. sub bestlink ($$) { #{{{
  296. my $page=shift;
  297. my $link=shift;
  298. my $cwd=$page;
  299. if ($link=~s/^\/+//) {
  300. # absolute links
  301. $cwd="";
  302. }
  303. do {
  304. my $l=$cwd;
  305. $l.="/" if length $l;
  306. $l.=$link;
  307. if (exists $links{$l}) {
  308. return $l;
  309. }
  310. elsif (exists $pagecase{lc $l}) {
  311. return $pagecase{lc $l};
  312. }
  313. } while $cwd=~s!/?[^/]+$!!;
  314. if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
  315. return "$config{userdir}/".lc($link);
  316. }
  317. #print STDERR "warning: page $page, broken link: $link\n";
  318. return "";
  319. } #}}}
  320. sub isinlinableimage ($) { #{{{
  321. my $file=shift;
  322. $file=~/\.(png|gif|jpg|jpeg)$/i;
  323. } #}}}
  324. sub pagetitle ($;$) { #{{{
  325. my $page=shift;
  326. my $unescaped=shift;
  327. if ($unescaped) {
  328. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  329. }
  330. else {
  331. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  332. }
  333. return $page;
  334. } #}}}
  335. sub titlepage ($) { #{{{
  336. my $title=shift;
  337. $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  338. return $title;
  339. } #}}}
  340. sub linkpage ($) { #{{{
  341. my $link=shift;
  342. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  343. return $link;
  344. } #}}}
  345. sub cgiurl (@) { #{{{
  346. my %params=@_;
  347. return $config{cgiurl}."?".
  348. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  349. } #}}}
  350. sub baseurl (;$) { #{{{
  351. my $page=shift;
  352. return "$config{url}/" if ! defined $page;
  353. $page=htmlpage($page);
  354. $page=~s/[^\/]+$//;
  355. $page=~s/[^\/]+\//..\//g;
  356. return $page;
  357. } #}}}
  358. sub abs2rel ($$) { #{{{
  359. # Work around very innefficient behavior in File::Spec if abs2rel
  360. # is passed two relative paths. It's much faster if paths are
  361. # absolute! (Debian bug #376658; fixed in debian unstable now)
  362. my $path="/".shift;
  363. my $base="/".shift;
  364. require File::Spec;
  365. my $ret=File::Spec->abs2rel($path, $base);
  366. $ret=~s/^// if defined $ret;
  367. return $ret;
  368. } #}}}
  369. sub displaytime ($) { #{{{
  370. my $time=shift;
  371. eval q{use POSIX};
  372. error($@) if $@;
  373. # strftime doesn't know about encodings, so make sure
  374. # its output is properly treated as utf8
  375. return decode_utf8(POSIX::strftime(
  376. $config{timeformat}, localtime($time)));
  377. } #}}}
  378. sub beautify_url ($) { #{{{
  379. my $url=shift;
  380. $url =~ s!/index.html$!/!;
  381. $url =~ s!^$!./!; # Browsers don't like empty links...
  382. return $url;
  383. } #}}}
  384. sub urlto ($$) { #{{{
  385. my $to=shift;
  386. my $from=shift;
  387. if (! length $to) {
  388. return beautify_url(baseurl($from));
  389. }
  390. if (! $destsources{$to}) {
  391. $to=htmlpage($to);
  392. }
  393. my $link = abs2rel($to, dirname(htmlpage($from)));
  394. return beautify_url($link);
  395. } #}}}
  396. sub htmllink ($$$;@) { #{{{
  397. my $lpage=shift; # the page doing the linking
  398. my $page=shift; # the page that will contain the link (different for inline)
  399. my $link=shift;
  400. my %opts=@_;
  401. my $bestlink;
  402. if (! $opts{forcesubpage}) {
  403. $bestlink=bestlink($lpage, $link);
  404. }
  405. else {
  406. $bestlink="$lpage/".lc($link);
  407. }
  408. my $linktext;
  409. if (defined $opts{linktext}) {
  410. $linktext=$opts{linktext};
  411. }
  412. else {
  413. $linktext=pagetitle(basename($link));
  414. }
  415. return "<span class=\"selflink\">$linktext</span>"
  416. if length $bestlink && $page eq $bestlink;
  417. if (! $destsources{$bestlink}) {
  418. $bestlink=htmlpage($bestlink);
  419. if (! $destsources{$bestlink}) {
  420. return $linktext unless length $config{cgiurl};
  421. return "<span><a href=\"".
  422. cgiurl(
  423. do => "create",
  424. page => pagetitle(lc($link), 1),
  425. from => $lpage
  426. ).
  427. "\">?</a>$linktext</span>"
  428. }
  429. }
  430. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  431. $bestlink=beautify_url($bestlink);
  432. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  433. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  434. }
  435. if (defined $opts{anchor}) {
  436. $bestlink.="#".$opts{anchor};
  437. }
  438. return "<a href=\"$bestlink\">$linktext</a>";
  439. } #}}}
  440. sub htmlize ($$$) { #{{{
  441. my $page=shift;
  442. my $type=shift;
  443. my $content=shift;
  444. if (exists $hooks{htmlize}{$type}) {
  445. $content=$hooks{htmlize}{$type}{call}->(
  446. page => $page,
  447. content => $content,
  448. );
  449. }
  450. else {
  451. error("htmlization of $type not supported");
  452. }
  453. run_hooks(sanitize => sub {
  454. $content=shift->(
  455. page => $page,
  456. content => $content,
  457. );
  458. });
  459. return $content;
  460. } #}}}
  461. sub linkify ($$$) { #{{{
  462. my $lpage=shift; # the page containing the links
  463. my $page=shift; # the page the link will end up on (different for inline)
  464. my $content=shift;
  465. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  466. defined $2
  467. ? ( $1
  468. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  469. : htmllink($lpage, $page, linkpage($3),
  470. anchor => $4, linktext => pagetitle($2)))
  471. : ( $1
  472. ? "[[$3".($4 ? "#$4" : "")."]]"
  473. : htmllink($lpage, $page, linkpage($3),
  474. anchor => $4))
  475. }eg;
  476. return $content;
  477. } #}}}
  478. my %preprocessing;
  479. our $preprocess_preview=0;
  480. sub preprocess ($$$;$$) { #{{{
  481. my $page=shift; # the page the data comes from
  482. my $destpage=shift; # the page the data will appear in (different for inline)
  483. my $content=shift;
  484. my $scan=shift;
  485. my $preview=shift;
  486. # Using local because it needs to be set within any nested calls
  487. # of this function.
  488. local $preprocess_preview=$preview if defined $preview;
  489. my $handle=sub {
  490. my $escape=shift;
  491. my $command=shift;
  492. my $params=shift;
  493. if (length $escape) {
  494. return "[[$command $params]]";
  495. }
  496. elsif (exists $hooks{preprocess}{$command}) {
  497. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  498. # Note: preserve order of params, some plugins may
  499. # consider it significant.
  500. my @params;
  501. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  502. my $key=$1;
  503. my $val;
  504. if (defined $2) {
  505. $val=$2;
  506. $val=~s/\r\n/\n/mg;
  507. $val=~s/^\n+//g;
  508. $val=~s/\n+$//g;
  509. }
  510. elsif (defined $3) {
  511. $val=$3;
  512. }
  513. elsif (defined $4) {
  514. $val=$4;
  515. }
  516. if (defined $key) {
  517. push @params, $key, $val;
  518. }
  519. else {
  520. push @params, $val, '';
  521. }
  522. }
  523. if ($preprocessing{$page}++ > 3) {
  524. # Avoid loops of preprocessed pages preprocessing
  525. # other pages that preprocess them, etc.
  526. #translators: The first parameter is a
  527. #translators: preprocessor directive name,
  528. #translators: the second a page name, the
  529. #translators: third a number.
  530. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  531. $command, $page, $preprocessing{$page}).
  532. "]]";
  533. }
  534. my $ret=$hooks{preprocess}{$command}{call}->(
  535. @params,
  536. page => $page,
  537. destpage => $destpage,
  538. preview => $preprocess_preview,
  539. );
  540. $preprocessing{$page}--;
  541. return $ret;
  542. }
  543. else {
  544. return "[[$command $params]]";
  545. }
  546. };
  547. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  548. return $content;
  549. } #}}}
  550. sub filter ($$) { #{{{
  551. my $page=shift;
  552. my $content=shift;
  553. run_hooks(filter => sub {
  554. $content=shift->(page => $page, content => $content);
  555. });
  556. return $content;
  557. } #}}}
  558. sub indexlink () { #{{{
  559. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  560. } #}}}
  561. sub lockwiki () { #{{{
  562. # Take an exclusive lock on the wiki to prevent multiple concurrent
  563. # run issues. The lock will be dropped on program exit.
  564. if (! -d $config{wikistatedir}) {
  565. mkdir($config{wikistatedir});
  566. }
  567. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  568. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  569. if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
  570. debug("wiki seems to be locked, waiting for lock");
  571. my $wait=600; # arbitrary, but don't hang forever to
  572. # prevent process pileup
  573. for (1..$wait) {
  574. return if flock(WIKILOCK, 2 | 4);
  575. sleep 1;
  576. }
  577. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  578. }
  579. } #}}}
  580. sub unlockwiki () { #{{{
  581. close WIKILOCK;
  582. } #}}}
  583. sub commit_hook_enabled () { #{{{
  584. open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
  585. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  586. if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  587. close COMMITLOCK;
  588. return 0;
  589. }
  590. close COMMITLOCK;
  591. return 1;
  592. } #}}}
  593. sub disable_commit_hook () { #{{{
  594. open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
  595. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  596. if (! flock(COMMITLOCK, 2)) { # LOCK_EX
  597. error("failed to get commit lock");
  598. }
  599. } #}}}
  600. sub enable_commit_hook () { #{{{
  601. close COMMITLOCK;
  602. } #}}}
  603. sub loadindex () { #{{{
  604. open (IN, "$config{wikistatedir}/index") || return;
  605. while (<IN>) {
  606. $_=possibly_foolish_untaint($_);
  607. chomp;
  608. my %items;
  609. $items{link}=[];
  610. $items{dest}=[];
  611. foreach my $i (split(/ /, $_)) {
  612. my ($item, $val)=split(/=/, $i, 2);
  613. push @{$items{$item}}, decode_entities($val);
  614. }
  615. next unless exists $items{src}; # skip bad lines for now
  616. my $page=pagename($items{src}[0]);
  617. if (! $config{rebuild}) {
  618. $pagesources{$page}=$items{src}[0];
  619. $pagemtime{$page}=$items{mtime}[0];
  620. $oldlinks{$page}=[@{$items{link}}];
  621. $links{$page}=[@{$items{link}}];
  622. $depends{$page}=$items{depends}[0] if exists $items{depends};
  623. $destsources{$_}=$page foreach @{$items{dest}};
  624. $renderedfiles{$page}=[@{$items{dest}}];
  625. $oldrenderedfiles{$page}=[@{$items{dest}}];
  626. $pagecase{lc $page}=$page;
  627. }
  628. $pagectime{$page}=$items{ctime}[0];
  629. }
  630. close IN;
  631. } #}}}
  632. sub saveindex () { #{{{
  633. run_hooks(savestate => sub { shift->() });
  634. if (! -d $config{wikistatedir}) {
  635. mkdir($config{wikistatedir});
  636. }
  637. my $newfile="$config{wikistatedir}/index.new";
  638. my $cleanup = sub { unlink($newfile) };
  639. open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
  640. foreach my $page (keys %pagemtime) {
  641. next unless $pagemtime{$page};
  642. my $line="mtime=$pagemtime{$page} ".
  643. "ctime=$pagectime{$page} ".
  644. "src=$pagesources{$page}";
  645. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  646. my %count;
  647. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  648. if (exists $depends{$page}) {
  649. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  650. }
  651. print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  652. }
  653. close OUT || error("failed saving to $newfile: $!", $cleanup);
  654. rename($newfile, "$config{wikistatedir}/index") ||
  655. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  656. } #}}}
  657. sub template_file ($) { #{{{
  658. my $template=shift;
  659. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  660. return "$dir/$template" if -e "$dir/$template";
  661. }
  662. return undef;
  663. } #}}}
  664. sub template_params (@) { #{{{
  665. my $filename=template_file(shift);
  666. if (! defined $filename) {
  667. return if wantarray;
  668. return "";
  669. }
  670. require HTML::Template;
  671. my @ret=(
  672. filter => sub {
  673. my $text_ref = shift;
  674. $$text_ref=&Encode::decode_utf8($$text_ref);
  675. },
  676. filename => $filename,
  677. loop_context_vars => 1,
  678. die_on_bad_params => 0,
  679. @_
  680. );
  681. return wantarray ? @ret : {@ret};
  682. } #}}}
  683. sub template ($;@) { #{{{
  684. HTML::Template->new(template_params(@_));
  685. } #}}}
  686. sub misctemplate ($$;@) { #{{{
  687. my $title=shift;
  688. my $pagebody=shift;
  689. my $template=template("misc.tmpl");
  690. $template->param(
  691. title => $title,
  692. indexlink => indexlink(),
  693. wikiname => $config{wikiname},
  694. pagebody => $pagebody,
  695. baseurl => baseurl(),
  696. @_,
  697. );
  698. run_hooks(pagetemplate => sub {
  699. shift->(page => "", destpage => "", template => $template);
  700. });
  701. return $template->output;
  702. }#}}}
  703. sub hook (@) { # {{{
  704. my %param=@_;
  705. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  706. error "hook requires type, call, and id parameters";
  707. }
  708. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  709. $hooks{$param{type}}{$param{id}}=\%param;
  710. } # }}}
  711. sub run_hooks ($$) { # {{{
  712. # Calls the given sub for each hook of the given type,
  713. # passing it the hook function to call.
  714. my $type=shift;
  715. my $sub=shift;
  716. if (exists $hooks{$type}) {
  717. my @deferred;
  718. foreach my $id (keys %{$hooks{$type}}) {
  719. if ($hooks{$type}{$id}{last}) {
  720. push @deferred, $id;
  721. next;
  722. }
  723. $sub->($hooks{$type}{$id}{call});
  724. }
  725. foreach my $id (@deferred) {
  726. $sub->($hooks{$type}{$id}{call});
  727. }
  728. }
  729. } #}}}
  730. sub globlist_to_pagespec ($) { #{{{
  731. my @globlist=split(' ', shift);
  732. my (@spec, @skip);
  733. foreach my $glob (@globlist) {
  734. if ($glob=~/^!(.*)/) {
  735. push @skip, $glob;
  736. }
  737. else {
  738. push @spec, $glob;
  739. }
  740. }
  741. my $spec=join(" or ", @spec);
  742. if (@skip) {
  743. my $skip=join(" and ", @skip);
  744. if (length $spec) {
  745. $spec="$skip and ($spec)";
  746. }
  747. else {
  748. $spec=$skip;
  749. }
  750. }
  751. return $spec;
  752. } #}}}
  753. sub is_globlist ($) { #{{{
  754. my $s=shift;
  755. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  756. } #}}}
  757. sub safequote ($) { #{{{
  758. my $s=shift;
  759. $s=~s/[{}]//g;
  760. return "q{$s}";
  761. } #}}}
  762. sub add_depends ($$) { #{{{
  763. my $page=shift;
  764. my $pagespec=shift;
  765. if (! exists $depends{$page}) {
  766. $depends{$page}=$pagespec;
  767. }
  768. else {
  769. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  770. }
  771. } # }}}
  772. sub file_pruned ($$) { #{{{
  773. require File::Spec;
  774. my $file=File::Spec->canonpath(shift);
  775. my $base=File::Spec->canonpath(shift);
  776. $file=~s#^\Q$base\E/*##;
  777. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  778. $file =~ m/$regexp/;
  779. } #}}}
  780. sub gettext { #{{{
  781. # Only use gettext in the rare cases it's needed.
  782. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  783. if (! $gettext_obj) {
  784. $gettext_obj=eval q{
  785. use Locale::gettext q{textdomain};
  786. Locale::gettext->domain('ikiwiki')
  787. };
  788. if ($@) {
  789. print STDERR "$@";
  790. $gettext_obj=undef;
  791. return shift;
  792. }
  793. }
  794. return $gettext_obj->get(shift);
  795. }
  796. else {
  797. return shift;
  798. }
  799. } #}}}
  800. sub pagespec_merge ($$) { #{{{
  801. my $a=shift;
  802. my $b=shift;
  803. return $a if $a eq $b;
  804. # Support for old-style GlobLists.
  805. if (is_globlist($a)) {
  806. $a=globlist_to_pagespec($a);
  807. }
  808. if (is_globlist($b)) {
  809. $b=globlist_to_pagespec($b);
  810. }
  811. return "($a) or ($b)";
  812. } #}}}
  813. sub pagespec_translate ($) { #{{{
  814. # This assumes that $page is in scope in the function
  815. # that evalulates the translated pagespec code.
  816. my $spec=shift;
  817. # Support for old-style GlobLists.
  818. if (is_globlist($spec)) {
  819. $spec=globlist_to_pagespec($spec);
  820. }
  821. # Convert spec to perl code.
  822. my $code="";
  823. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  824. my $word=$1;
  825. if (lc $word eq "and") {
  826. $code.=" &&";
  827. }
  828. elsif (lc $word eq "or") {
  829. $code.=" ||";
  830. }
  831. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  832. $code.=" ".$word;
  833. }
  834. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  835. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  836. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
  837. }
  838. else {
  839. $code.=" 0";
  840. }
  841. }
  842. else {
  843. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
  844. }
  845. }
  846. return $code;
  847. } #}}}
  848. sub pagespec_match ($$;$) { #{{{
  849. my $page=shift;
  850. my $spec=shift;
  851. my $from=shift;
  852. return eval pagespec_translate($spec);
  853. } #}}}
  854. package IkiWiki::PageSpec;
  855. sub match_glob ($$$) { #{{{
  856. my $page=shift;
  857. my $glob=shift;
  858. my $from=shift;
  859. if (! defined $from){
  860. $from = "";
  861. }
  862. # relative matching
  863. if ($glob =~ m!^\./!) {
  864. $from=~s!/?[^/]+$!!;
  865. $glob=~s!^\./!!;
  866. $glob="$from/$glob" if length $from;
  867. }
  868. # turn glob into safe regexp
  869. $glob=quotemeta($glob);
  870. $glob=~s/\\\*/.*/g;
  871. $glob=~s/\\\?/./g;
  872. return $page=~/^$glob$/i;
  873. } #}}}
  874. sub match_link ($$$) { #{{{
  875. my $page=shift;
  876. my $link=lc(shift);
  877. my $from=shift;
  878. if (! defined $from){
  879. $from = "";
  880. }
  881. # relative matching
  882. if ($link =~ m!^\.! && defined $from) {
  883. $from=~s!/?[^/]+$!!;
  884. $link=~s!^\./!!;
  885. $link="$from/$link" if length $from;
  886. }
  887. my $links = $IkiWiki::links{$page} or return undef;
  888. return 0 unless @$links;
  889. my $bestlink = IkiWiki::bestlink($from, $link);
  890. return 0 unless length $bestlink;
  891. foreach my $p (@$links) {
  892. return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
  893. }
  894. return 0;
  895. } #}}}
  896. sub match_backlink ($$$) { #{{{
  897. match_link($_[1], $_[0], $_[3]);
  898. } #}}}
  899. sub match_created_before ($$$) { #{{{
  900. my $page=shift;
  901. my $testpage=shift;
  902. if (exists $IkiWiki::pagectime{$testpage}) {
  903. return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
  904. }
  905. else {
  906. return 0;
  907. }
  908. } #}}}
  909. sub match_created_after ($$$) { #{{{
  910. my $page=shift;
  911. my $testpage=shift;
  912. if (exists $IkiWiki::pagectime{$testpage}) {
  913. return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
  914. }
  915. else {
  916. return 0;
  917. }
  918. } #}}}
  919. sub match_creation_day ($$$) { #{{{
  920. return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
  921. } #}}}
  922. sub match_creation_month ($$$) { #{{{
  923. return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
  924. } #}}}
  925. sub match_creation_year ($$$) { #{{{
  926. return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
  927. } #}}}
  928. 1