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