summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 1c310d39157d1a5fd29e37b7b1fabaec87b72391 (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);
  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. wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
  31. wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
  32. web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  33. verbose => 0,
  34. syslog => 0,
  35. wikiname => "wiki",
  36. default_pageext => "mdwn",
  37. cgi => 0,
  38. post_commit => 0,
  39. rcs => '',
  40. notify => 0,
  41. url => '',
  42. cgiurl => '',
  43. historyurl => '',
  44. diffurl => '',
  45. rss => 0,
  46. atom => 0,
  47. discussion => 1,
  48. rebuild => 0,
  49. refresh => 0,
  50. getctime => 0,
  51. w3mmode => 0,
  52. wrapper => undef,
  53. wrappermode => undef,
  54. svnrepo => undef,
  55. svnpath => "trunk",
  56. gitorigin_branch => "origin",
  57. gitmaster_branch => "master",
  58. srcdir => undef,
  59. destdir => undef,
  60. pingurl => [],
  61. templatedir => "$installdir/share/ikiwiki/templates",
  62. underlaydir => "$installdir/share/ikiwiki/basewiki",
  63. setup => undef,
  64. adminuser => undef,
  65. adminemail => undef,
  66. plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
  67. lockedit conditional}],
  68. timeformat => '%c',
  69. locale => undef,
  70. sslcookie => 0,
  71. httpauth => 0,
  72. userdir => "",
  73. usedirs => 0,
  74. numbacklinks => 10,
  75. } #}}}
  76. sub checkconfig () { #{{{
  77. # locale stuff; avoid LC_ALL since it overrides everything
  78. if (defined $ENV{LC_ALL}) {
  79. $ENV{LANG} = $ENV{LC_ALL};
  80. delete $ENV{LC_ALL};
  81. }
  82. if (defined $config{locale}) {
  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 in $config{srcdir} or $config{underlaydir}");
  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. # strftime doesn't know about encodings, so make sure
  372. # its output is properly treated as utf8
  373. return decode_utf8(POSIX::strftime(
  374. $config{timeformat}, localtime($time)));
  375. } #}}}
  376. sub beautify_url ($) { #{{{
  377. my $url=shift;
  378. $url =~ s!/index.html$!/!;
  379. $url =~ s!^$!./!; # Browsers don't like empty links...
  380. return $url;
  381. } #}}}
  382. sub urlto ($$) { #{{{
  383. my $to=shift;
  384. my $from=shift;
  385. if (! length $to) {
  386. return beautify_url(baseurl($from));
  387. }
  388. if (! $destsources{$to}) {
  389. $to=htmlpage($to);
  390. }
  391. my $link = abs2rel($to, dirname(htmlpage($from)));
  392. return beautify_url($link);
  393. } #}}}
  394. sub htmllink ($$$;@) { #{{{
  395. my $lpage=shift; # the page doing the linking
  396. my $page=shift; # the page that will contain the link (different for inline)
  397. my $link=shift;
  398. my %opts=@_;
  399. my $bestlink;
  400. if (! $opts{forcesubpage}) {
  401. $bestlink=bestlink($lpage, $link);
  402. }
  403. else {
  404. $bestlink="$lpage/".lc($link);
  405. }
  406. my $linktext;
  407. if (defined $opts{linktext}) {
  408. $linktext=$opts{linktext};
  409. }
  410. else {
  411. $linktext=pagetitle(basename($link));
  412. }
  413. return "<span class=\"selflink\">$linktext</span>"
  414. if length $bestlink && $page eq $bestlink;
  415. if (! $destsources{$bestlink}) {
  416. $bestlink=htmlpage($bestlink);
  417. if (! $destsources{$bestlink}) {
  418. return $linktext unless length $config{cgiurl};
  419. return "<span><a href=\"".
  420. cgiurl(
  421. do => "create",
  422. page => pagetitle(lc($link), 1),
  423. from => $lpage
  424. ).
  425. "\">?</a>$linktext</span>"
  426. }
  427. }
  428. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  429. $bestlink=beautify_url($bestlink);
  430. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  431. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  432. }
  433. if (defined $opts{anchor}) {
  434. $bestlink.="#".$opts{anchor};
  435. }
  436. return "<a href=\"$bestlink\">$linktext</a>";
  437. } #}}}
  438. sub htmlize ($$$) { #{{{
  439. my $page=shift;
  440. my $type=shift;
  441. my $content=shift;
  442. if (exists $hooks{htmlize}{$type}) {
  443. $content=$hooks{htmlize}{$type}{call}->(
  444. page => $page,
  445. content => $content,
  446. );
  447. }
  448. else {
  449. error("htmlization of $type not supported");
  450. }
  451. run_hooks(sanitize => sub {
  452. $content=shift->(
  453. page => $page,
  454. content => $content,
  455. );
  456. });
  457. return $content;
  458. } #}}}
  459. sub linkify ($$$) { #{{{
  460. my $lpage=shift; # the page containing the links
  461. my $page=shift; # the page the link will end up on (different for inline)
  462. my $content=shift;
  463. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  464. defined $2
  465. ? ( $1
  466. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  467. : htmllink($lpage, $page, linkpage($3),
  468. anchor => $4, linktext => pagetitle($2)))
  469. : ( $1
  470. ? "[[$3".($4 ? "#$4" : "")."]]"
  471. : htmllink($lpage, $page, linkpage($3),
  472. anchor => $4))
  473. }eg;
  474. return $content;
  475. } #}}}
  476. my %preprocessing;
  477. our $preprocess_preview=0;
  478. sub preprocess ($$$;$$) { #{{{
  479. my $page=shift; # the page the data comes from
  480. my $destpage=shift; # the page the data will appear in (different for inline)
  481. my $content=shift;
  482. my $scan=shift;
  483. my $preview=shift;
  484. # Using local because it needs to be set within any nested calls
  485. # of this function.
  486. local $preprocess_preview=$preview if defined $preview;
  487. my $handle=sub {
  488. my $escape=shift;
  489. my $command=shift;
  490. my $params=shift;
  491. if (length $escape) {
  492. return "[[$command $params]]";
  493. }
  494. elsif (exists $hooks{preprocess}{$command}) {
  495. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  496. # Note: preserve order of params, some plugins may
  497. # consider it significant.
  498. my @params;
  499. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  500. my $key=$1;
  501. my $val;
  502. if (defined $2) {
  503. $val=$2;
  504. $val=~s/\r\n/\n/mg;
  505. $val=~s/^\n+//g;
  506. $val=~s/\n+$//g;
  507. }
  508. elsif (defined $3) {
  509. $val=$3;
  510. }
  511. elsif (defined $4) {
  512. $val=$4;
  513. }
  514. if (defined $key) {
  515. push @params, $key, $val;
  516. }
  517. else {
  518. push @params, $val, '';
  519. }
  520. }
  521. if ($preprocessing{$page}++ > 3) {
  522. # Avoid loops of preprocessed pages preprocessing
  523. # other pages that preprocess them, etc.
  524. #translators: The first parameter is a
  525. #translators: preprocessor directive name,
  526. #translators: the second a page name, the
  527. #translators: third a number.
  528. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  529. $command, $page, $preprocessing{$page}).
  530. "]]";
  531. }
  532. my $ret=$hooks{preprocess}{$command}{call}->(
  533. @params,
  534. page => $page,
  535. destpage => $destpage,
  536. preview => $preprocess_preview,
  537. );
  538. $preprocessing{$page}--;
  539. return $ret;
  540. }
  541. else {
  542. return "[[$command $params]]";
  543. }
  544. };
  545. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  546. return $content;
  547. } #}}}
  548. sub filter ($$) { #{{{
  549. my $page=shift;
  550. my $content=shift;
  551. run_hooks(filter => sub {
  552. $content=shift->(page => $page, content => $content);
  553. });
  554. return $content;
  555. } #}}}
  556. sub indexlink () { #{{{
  557. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  558. } #}}}
  559. sub lockwiki () { #{{{
  560. # Take an exclusive lock on the wiki to prevent multiple concurrent
  561. # run issues. The lock will be dropped on program exit.
  562. if (! -d $config{wikistatedir}) {
  563. mkdir($config{wikistatedir});
  564. }
  565. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  566. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  567. if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
  568. debug("wiki seems to be locked, waiting for lock");
  569. my $wait=600; # arbitrary, but don't hang forever to
  570. # prevent process pileup
  571. for (1..$wait) {
  572. return if flock(WIKILOCK, 2 | 4);
  573. sleep 1;
  574. }
  575. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  576. }
  577. } #}}}
  578. sub unlockwiki () { #{{{
  579. close WIKILOCK;
  580. } #}}}
  581. sub commit_hook_enabled () { #{{{
  582. open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
  583. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  584. if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  585. close COMMITLOCK;
  586. return 0;
  587. }
  588. close COMMITLOCK;
  589. return 1;
  590. } #}}}
  591. sub disable_commit_hook () { #{{{
  592. open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
  593. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  594. if (! flock(COMMITLOCK, 2)) { # LOCK_EX
  595. error("failed to get commit lock");
  596. }
  597. } #}}}
  598. sub enable_commit_hook () { #{{{
  599. close COMMITLOCK;
  600. } #}}}
  601. sub loadindex () { #{{{
  602. open (IN, "$config{wikistatedir}/index") || return;
  603. while (<IN>) {
  604. $_=possibly_foolish_untaint($_);
  605. chomp;
  606. my %items;
  607. $items{link}=[];
  608. $items{dest}=[];
  609. foreach my $i (split(/ /, $_)) {
  610. my ($item, $val)=split(/=/, $i, 2);
  611. push @{$items{$item}}, decode_entities($val);
  612. }
  613. next unless exists $items{src}; # skip bad lines for now
  614. my $page=pagename($items{src}[0]);
  615. if (! $config{rebuild}) {
  616. $pagesources{$page}=$items{src}[0];
  617. $pagemtime{$page}=$items{mtime}[0];
  618. $oldlinks{$page}=[@{$items{link}}];
  619. $links{$page}=[@{$items{link}}];
  620. $depends{$page}=$items{depends}[0] if exists $items{depends};
  621. $destsources{$_}=$page foreach @{$items{dest}};
  622. $renderedfiles{$page}=[@{$items{dest}}];
  623. $oldrenderedfiles{$page}=[@{$items{dest}}];
  624. $pagecase{lc $page}=$page;
  625. }
  626. $pagectime{$page}=$items{ctime}[0];
  627. }
  628. close IN;
  629. } #}}}
  630. sub saveindex () { #{{{
  631. run_hooks(savestate => sub { shift->() });
  632. if (! -d $config{wikistatedir}) {
  633. mkdir($config{wikistatedir});
  634. }
  635. my $newfile="$config{wikistatedir}/index.new";
  636. my $cleanup = sub { unlink($newfile) };
  637. open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
  638. foreach my $page (keys %pagemtime) {
  639. next unless $pagemtime{$page};
  640. my $line="mtime=$pagemtime{$page} ".
  641. "ctime=$pagectime{$page} ".
  642. "src=$pagesources{$page}";
  643. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  644. my %count;
  645. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  646. if (exists $depends{$page}) {
  647. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  648. }
  649. print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  650. }
  651. close OUT || error("failed saving to $newfile: $!", $cleanup);
  652. rename($newfile, "$config{wikistatedir}/index") ||
  653. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  654. } #}}}
  655. sub template_file ($) { #{{{
  656. my $template=shift;
  657. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  658. return "$dir/$template" if -e "$dir/$template";
  659. }
  660. return undef;
  661. } #}}}
  662. sub template_params (@) { #{{{
  663. my $filename=template_file(shift);
  664. if (! defined $filename) {
  665. return if wantarray;
  666. return "";
  667. }
  668. require HTML::Template;
  669. my @ret=(
  670. filter => sub {
  671. my $text_ref = shift;
  672. $$text_ref=&Encode::decode_utf8($$text_ref);
  673. },
  674. filename => $filename,
  675. loop_context_vars => 1,
  676. die_on_bad_params => 0,
  677. @_
  678. );
  679. return wantarray ? @ret : {@ret};
  680. } #}}}
  681. sub template ($;@) { #{{{
  682. HTML::Template->new(template_params(@_));
  683. } #}}}
  684. sub misctemplate ($$;@) { #{{{
  685. my $title=shift;
  686. my $pagebody=shift;
  687. my $template=template("misc.tmpl");
  688. $template->param(
  689. title => $title,
  690. indexlink => indexlink(),
  691. wikiname => $config{wikiname},
  692. pagebody => $pagebody,
  693. baseurl => baseurl(),
  694. @_,
  695. );
  696. run_hooks(pagetemplate => sub {
  697. shift->(page => "", destpage => "", template => $template);
  698. });
  699. return $template->output;
  700. }#}}}
  701. sub hook (@) { # {{{
  702. my %param=@_;
  703. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  704. error "hook requires type, call, and id parameters";
  705. }
  706. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  707. $hooks{$param{type}}{$param{id}}=\%param;
  708. } # }}}
  709. sub run_hooks ($$) { # {{{
  710. # Calls the given sub for each hook of the given type,
  711. # passing it the hook function to call.
  712. my $type=shift;
  713. my $sub=shift;
  714. if (exists $hooks{$type}) {
  715. my @deferred;
  716. foreach my $id (keys %{$hooks{$type}}) {
  717. if ($hooks{$type}{$id}{last}) {
  718. push @deferred, $id;
  719. next;
  720. }
  721. $sub->($hooks{$type}{$id}{call});
  722. }
  723. foreach my $id (@deferred) {
  724. $sub->($hooks{$type}{$id}{call});
  725. }
  726. }
  727. } #}}}
  728. sub globlist_to_pagespec ($) { #{{{
  729. my @globlist=split(' ', shift);
  730. my (@spec, @skip);
  731. foreach my $glob (@globlist) {
  732. if ($glob=~/^!(.*)/) {
  733. push @skip, $glob;
  734. }
  735. else {
  736. push @spec, $glob;
  737. }
  738. }
  739. my $spec=join(" or ", @spec);
  740. if (@skip) {
  741. my $skip=join(" and ", @skip);
  742. if (length $spec) {
  743. $spec="$skip and ($spec)";
  744. }
  745. else {
  746. $spec=$skip;
  747. }
  748. }
  749. return $spec;
  750. } #}}}
  751. sub is_globlist ($) { #{{{
  752. my $s=shift;
  753. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  754. } #}}}
  755. sub safequote ($) { #{{{
  756. my $s=shift;
  757. $s=~s/[{}]//g;
  758. return "q{$s}";
  759. } #}}}
  760. sub add_depends ($$) { #{{{
  761. my $page=shift;
  762. my $pagespec=shift;
  763. if (! exists $depends{$page}) {
  764. $depends{$page}=$pagespec;
  765. }
  766. else {
  767. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  768. }
  769. } # }}}
  770. sub file_pruned ($$) { #{{{
  771. require File::Spec;
  772. my $file=File::Spec->canonpath(shift);
  773. my $base=File::Spec->canonpath(shift);
  774. $file=~s#^\Q$base\E/*##;
  775. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  776. $file =~ m/$regexp/;
  777. } #}}}
  778. sub gettext { #{{{
  779. # Only use gettext in the rare cases it's needed.
  780. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  781. if (! $gettext_obj) {
  782. $gettext_obj=eval q{
  783. use Locale::gettext q{textdomain};
  784. Locale::gettext->domain('ikiwiki')
  785. };
  786. if ($@) {
  787. print STDERR "$@";
  788. $gettext_obj=undef;
  789. return shift;
  790. }
  791. }
  792. return $gettext_obj->get(shift);
  793. }
  794. else {
  795. return shift;
  796. }
  797. } #}}}
  798. sub pagespec_merge ($$) { #{{{
  799. my $a=shift;
  800. my $b=shift;
  801. return $a if $a eq $b;
  802. # Support for old-style GlobLists.
  803. if (is_globlist($a)) {
  804. $a=globlist_to_pagespec($a);
  805. }
  806. if (is_globlist($b)) {
  807. $b=globlist_to_pagespec($b);
  808. }
  809. return "($a) or ($b)";
  810. } #}}}
  811. sub pagespec_translate ($) { #{{{
  812. # This assumes that $page is in scope in the function
  813. # that evalulates the translated pagespec code.
  814. my $spec=shift;
  815. # Support for old-style GlobLists.
  816. if (is_globlist($spec)) {
  817. $spec=globlist_to_pagespec($spec);
  818. }
  819. # Convert spec to perl code.
  820. my $code="";
  821. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  822. my $word=$1;
  823. if (lc $word eq "and") {
  824. $code.=" &&";
  825. }
  826. elsif (lc $word eq "or") {
  827. $code.=" ||";
  828. }
  829. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  830. $code.=" ".$word;
  831. }
  832. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  833. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  834. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
  835. }
  836. else {
  837. $code.=" 0";
  838. }
  839. }
  840. else {
  841. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
  842. }
  843. }
  844. return $code;
  845. } #}}}
  846. sub pagespec_match ($$;$) { #{{{
  847. my $page=shift;
  848. my $spec=shift;
  849. my $from=shift;
  850. return eval pagespec_translate($spec);
  851. } #}}}
  852. package IkiWiki::PageSpec;
  853. sub match_glob ($$$) { #{{{
  854. my $page=shift;
  855. my $glob=shift;
  856. my $from=shift;
  857. if (! defined $from){
  858. $from = "";
  859. }
  860. # relative matching
  861. if ($glob =~ m!^\./!) {
  862. $from=~s!/?[^/]+$!!;
  863. $glob=~s!^\./!!;
  864. $glob="$from/$glob" if length $from;
  865. }
  866. # turn glob into safe regexp
  867. $glob=quotemeta($glob);
  868. $glob=~s/\\\*/.*/g;
  869. $glob=~s/\\\?/./g;
  870. return $page=~/^$glob$/i;
  871. } #}}}
  872. sub match_link ($$$) { #{{{
  873. my $page=shift;
  874. my $link=lc(shift);
  875. my $from=shift;
  876. if (! defined $from){
  877. $from = "";
  878. }
  879. # relative matching
  880. if ($link =~ m!^\.! && defined $from) {
  881. $from=~s!/?[^/]+$!!;
  882. $link=~s!^\./!!;
  883. $link="$from/$link" if length $from;
  884. }
  885. my $links = $IkiWiki::links{$page} or return undef;
  886. return 0 unless @$links;
  887. my $bestlink = IkiWiki::bestlink($from, $link);
  888. return 0 unless length $bestlink;
  889. foreach my $p (@$links) {
  890. return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
  891. }
  892. return 0;
  893. } #}}}
  894. sub match_backlink ($$$) { #{{{
  895. match_link($_[1], $_[0], $_[3]);
  896. } #}}}
  897. sub match_created_before ($$$) { #{{{
  898. my $page=shift;
  899. my $testpage=shift;
  900. if (exists $IkiWiki::pagectime{$testpage}) {
  901. return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
  902. }
  903. else {
  904. return 0;
  905. }
  906. } #}}}
  907. sub match_created_after ($$$) { #{{{
  908. my $page=shift;
  909. my $testpage=shift;
  910. if (exists $IkiWiki::pagectime{$testpage}) {
  911. return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
  912. }
  913. else {
  914. return 0;
  915. }
  916. } #}}}
  917. sub match_creation_day ($$$) { #{{{
  918. return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
  919. } #}}}
  920. sub match_creation_month ($$$) { #{{{
  921. return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
  922. } #}}}
  923. sub match_creation_year ($$$) { #{{{
  924. return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
  925. } #}}}
  926. 1