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