summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 8f9bd990a02c48a26a249e36e3df245807dbedec (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 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
  464. : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
  465. }eg;
  466. return $content;
  467. } #}}}
  468. my %preprocessing;
  469. our $preprocess_preview=0;
  470. sub preprocess ($$$;$$) { #{{{
  471. my $page=shift; # the page the data comes from
  472. my $destpage=shift; # the page the data will appear in (different for inline)
  473. my $content=shift;
  474. my $scan=shift;
  475. my $preview=shift;
  476. # Using local because it needs to be set within any nested calls
  477. # of this function.
  478. local $preprocess_preview=$preview if defined $preview;
  479. my $handle=sub {
  480. my $escape=shift;
  481. my $command=shift;
  482. my $params=shift;
  483. if (length $escape) {
  484. return "[[$command $params]]";
  485. }
  486. elsif (exists $hooks{preprocess}{$command}) {
  487. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  488. # Note: preserve order of params, some plugins may
  489. # consider it significant.
  490. my @params;
  491. while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
  492. my $key=$1;
  493. my $val;
  494. if (defined $2) {
  495. $val=$2;
  496. $val=~s/\r\n/\n/mg;
  497. $val=~s/^\n+//g;
  498. $val=~s/\n+$//g;
  499. }
  500. elsif (defined $3) {
  501. $val=$3;
  502. }
  503. elsif (defined $4) {
  504. $val=$4;
  505. }
  506. if (defined $key) {
  507. push @params, $key, $val;
  508. }
  509. else {
  510. push @params, $val, '';
  511. }
  512. }
  513. if ($preprocessing{$page}++ > 3) {
  514. # Avoid loops of preprocessed pages preprocessing
  515. # other pages that preprocess them, etc.
  516. #translators: The first parameter is a
  517. #translators: preprocessor directive name,
  518. #translators: the second a page name, the
  519. #translators: third a number.
  520. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  521. $command, $page, $preprocessing{$page}).
  522. "]]";
  523. }
  524. my $ret=$hooks{preprocess}{$command}{call}->(
  525. @params,
  526. page => $page,
  527. destpage => $destpage,
  528. preview => $preprocess_preview,
  529. );
  530. $preprocessing{$page}--;
  531. return $ret;
  532. }
  533. else {
  534. return "[[$command $params]]";
  535. }
  536. };
  537. $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
  538. return $content;
  539. } #}}}
  540. sub filter ($$) { #{{{
  541. my $page=shift;
  542. my $content=shift;
  543. run_hooks(filter => sub {
  544. $content=shift->(page => $page, content => $content);
  545. });
  546. return $content;
  547. } #}}}
  548. sub indexlink () { #{{{
  549. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  550. } #}}}
  551. sub lockwiki () { #{{{
  552. # Take an exclusive lock on the wiki to prevent multiple concurrent
  553. # run issues. The lock will be dropped on program exit.
  554. if (! -d $config{wikistatedir}) {
  555. mkdir($config{wikistatedir});
  556. }
  557. open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
  558. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  559. if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
  560. debug("wiki seems to be locked, waiting for lock");
  561. my $wait=600; # arbitrary, but don't hang forever to
  562. # prevent process pileup
  563. for (1..$wait) {
  564. return if flock(WIKILOCK, 2 | 4);
  565. sleep 1;
  566. }
  567. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  568. }
  569. } #}}}
  570. sub unlockwiki () { #{{{
  571. close WIKILOCK;
  572. } #}}}
  573. sub commit_hook_enabled () { #{{{
  574. open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
  575. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  576. if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  577. close COMMITLOCK;
  578. return 0;
  579. }
  580. close COMMITLOCK;
  581. return 1;
  582. } #}}}
  583. sub disable_commit_hook () { #{{{
  584. open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
  585. error ("cannot write to $config{wikistatedir}/commitlock: $!");
  586. if (! flock(COMMITLOCK, 2)) { # LOCK_EX
  587. error("failed to get commit lock");
  588. }
  589. } #}}}
  590. sub enable_commit_hook () { #{{{
  591. close COMMITLOCK;
  592. } #}}}
  593. sub loadindex () { #{{{
  594. open (IN, "$config{wikistatedir}/index") || return;
  595. while (<IN>) {
  596. $_=possibly_foolish_untaint($_);
  597. chomp;
  598. my %items;
  599. $items{link}=[];
  600. $items{dest}=[];
  601. foreach my $i (split(/ /, $_)) {
  602. my ($item, $val)=split(/=/, $i, 2);
  603. push @{$items{$item}}, decode_entities($val);
  604. }
  605. next unless exists $items{src}; # skip bad lines for now
  606. my $page=pagename($items{src}[0]);
  607. if (! $config{rebuild}) {
  608. $pagesources{$page}=$items{src}[0];
  609. $pagemtime{$page}=$items{mtime}[0];
  610. $oldlinks{$page}=[@{$items{link}}];
  611. $links{$page}=[@{$items{link}}];
  612. $depends{$page}=$items{depends}[0] if exists $items{depends};
  613. $renderedfiles{$page}=[@{$items{dest}}];
  614. $oldrenderedfiles{$page}=[@{$items{dest}}];
  615. $pagecase{lc $page}=$page;
  616. }
  617. $pagectime{$page}=$items{ctime}[0];
  618. }
  619. close IN;
  620. } #}}}
  621. sub saveindex () { #{{{
  622. run_hooks(savestate => sub { shift->() });
  623. if (! -d $config{wikistatedir}) {
  624. mkdir($config{wikistatedir});
  625. }
  626. my $newfile="$config{wikistatedir}/index.new";
  627. my $cleanup = sub { unlink($newfile) };
  628. open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
  629. foreach my $page (keys %pagemtime) {
  630. next unless $pagemtime{$page};
  631. my $line="mtime=$pagemtime{$page} ".
  632. "ctime=$pagectime{$page} ".
  633. "src=$pagesources{$page}";
  634. $line.=" dest=$_" foreach @{$renderedfiles{$page}};
  635. my %count;
  636. $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
  637. if (exists $depends{$page}) {
  638. $line.=" depends=".encode_entities($depends{$page}, " \t\n");
  639. }
  640. print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
  641. }
  642. close OUT || error("failed saving to $newfile: $!", $cleanup);
  643. rename($newfile, "$config{wikistatedir}/index") ||
  644. error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
  645. } #}}}
  646. sub template_file ($) { #{{{
  647. my $template=shift;
  648. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  649. return "$dir/$template" if -e "$dir/$template";
  650. }
  651. return undef;
  652. } #}}}
  653. sub template_params (@) { #{{{
  654. my $filename=template_file(shift);
  655. if (! defined $filename) {
  656. return if wantarray;
  657. return "";
  658. }
  659. require HTML::Template;
  660. my @ret=(
  661. filter => sub {
  662. my $text_ref = shift;
  663. $$text_ref=&Encode::decode_utf8($$text_ref);
  664. },
  665. filename => $filename,
  666. loop_context_vars => 1,
  667. die_on_bad_params => 0,
  668. @_
  669. );
  670. return wantarray ? @ret : {@ret};
  671. } #}}}
  672. sub template ($;@) { #{{{
  673. HTML::Template->new(template_params(@_));
  674. } #}}}
  675. sub misctemplate ($$;@) { #{{{
  676. my $title=shift;
  677. my $pagebody=shift;
  678. my $template=template("misc.tmpl");
  679. $template->param(
  680. title => $title,
  681. indexlink => indexlink(),
  682. wikiname => $config{wikiname},
  683. pagebody => $pagebody,
  684. baseurl => baseurl(),
  685. @_,
  686. );
  687. run_hooks(pagetemplate => sub {
  688. shift->(page => "", destpage => "", template => $template);
  689. });
  690. return $template->output;
  691. }#}}}
  692. sub hook (@) { # {{{
  693. my %param=@_;
  694. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  695. error "hook requires type, call, and id parameters";
  696. }
  697. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  698. $hooks{$param{type}}{$param{id}}=\%param;
  699. } # }}}
  700. sub run_hooks ($$) { # {{{
  701. # Calls the given sub for each hook of the given type,
  702. # passing it the hook function to call.
  703. my $type=shift;
  704. my $sub=shift;
  705. if (exists $hooks{$type}) {
  706. my @deferred;
  707. foreach my $id (keys %{$hooks{$type}}) {
  708. if ($hooks{$type}{$id}{last}) {
  709. push @deferred, $id;
  710. next;
  711. }
  712. $sub->($hooks{$type}{$id}{call});
  713. }
  714. foreach my $id (@deferred) {
  715. $sub->($hooks{$type}{$id}{call});
  716. }
  717. }
  718. } #}}}
  719. sub globlist_to_pagespec ($) { #{{{
  720. my @globlist=split(' ', shift);
  721. my (@spec, @skip);
  722. foreach my $glob (@globlist) {
  723. if ($glob=~/^!(.*)/) {
  724. push @skip, $glob;
  725. }
  726. else {
  727. push @spec, $glob;
  728. }
  729. }
  730. my $spec=join(" or ", @spec);
  731. if (@skip) {
  732. my $skip=join(" and ", @skip);
  733. if (length $spec) {
  734. $spec="$skip and ($spec)";
  735. }
  736. else {
  737. $spec=$skip;
  738. }
  739. }
  740. return $spec;
  741. } #}}}
  742. sub is_globlist ($) { #{{{
  743. my $s=shift;
  744. $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
  745. } #}}}
  746. sub safequote ($) { #{{{
  747. my $s=shift;
  748. $s=~s/[{}]//g;
  749. return "q{$s}";
  750. } #}}}
  751. sub add_depends ($$) { #{{{
  752. my $page=shift;
  753. my $pagespec=shift;
  754. if (! exists $depends{$page}) {
  755. $depends{$page}=$pagespec;
  756. }
  757. else {
  758. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  759. }
  760. } # }}}
  761. sub file_pruned ($$) { #{{{
  762. require File::Spec;
  763. my $file=File::Spec->canonpath(shift);
  764. my $base=File::Spec->canonpath(shift);
  765. $file=~s#^\Q$base\E/*##;
  766. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  767. $file =~ m/$regexp/;
  768. } #}}}
  769. sub gettext { #{{{
  770. # Only use gettext in the rare cases it's needed.
  771. if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
  772. if (! $gettext_obj) {
  773. $gettext_obj=eval q{
  774. use Locale::gettext q{textdomain};
  775. Locale::gettext->domain('ikiwiki')
  776. };
  777. if ($@) {
  778. print STDERR "$@";
  779. $gettext_obj=undef;
  780. return shift;
  781. }
  782. }
  783. return $gettext_obj->get(shift);
  784. }
  785. else {
  786. return shift;
  787. }
  788. } #}}}
  789. sub pagespec_merge ($$) { #{{{
  790. my $a=shift;
  791. my $b=shift;
  792. return $a if $a eq $b;
  793. # Support for old-style GlobLists.
  794. if (is_globlist($a)) {
  795. $a=globlist_to_pagespec($a);
  796. }
  797. if (is_globlist($b)) {
  798. $b=globlist_to_pagespec($b);
  799. }
  800. return "($a) or ($b)";
  801. } #}}}
  802. sub pagespec_translate ($) { #{{{
  803. # This assumes that $page is in scope in the function
  804. # that evalulates the translated pagespec code.
  805. my $spec=shift;
  806. # Support for old-style GlobLists.
  807. if (is_globlist($spec)) {
  808. $spec=globlist_to_pagespec($spec);
  809. }
  810. # Convert spec to perl code.
  811. my $code="";
  812. while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
  813. my $word=$1;
  814. if (lc $word eq "and") {
  815. $code.=" &&";
  816. }
  817. elsif (lc $word eq "or") {
  818. $code.=" ||";
  819. }
  820. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  821. $code.=" ".$word;
  822. }
  823. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  824. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  825. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
  826. }
  827. else {
  828. $code.=" 0";
  829. }
  830. }
  831. else {
  832. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
  833. }
  834. }
  835. return $code;
  836. } #}}}
  837. sub pagespec_match ($$;$) { #{{{
  838. my $page=shift;
  839. my $spec=shift;
  840. my $from=shift;
  841. return eval pagespec_translate($spec);
  842. } #}}}
  843. package IkiWiki::PageSpec;
  844. sub match_glob ($$$) { #{{{
  845. my $page=shift;
  846. my $glob=shift;
  847. my $from=shift;
  848. if (! defined $from){
  849. $from = "";
  850. }
  851. # relative matching
  852. if ($glob =~ m!^\./!) {
  853. $from=~s!/?[^/]+$!!;
  854. $glob=~s!^\./!!;
  855. $glob="$from/$glob" if length $from;
  856. }
  857. # turn glob into safe regexp
  858. $glob=quotemeta($glob);
  859. $glob=~s/\\\*/.*/g;
  860. $glob=~s/\\\?/./g;
  861. return $page=~/^$glob$/i;
  862. } #}}}
  863. sub match_link ($$$) { #{{{
  864. my $page=shift;
  865. my $link=lc(shift);
  866. my $from=shift;
  867. if (! defined $from){
  868. $from = "";
  869. }
  870. # relative matching
  871. if ($link =~ m!^\.! && defined $from) {
  872. $from=~s!/?[^/]+$!!;
  873. $link=~s!^\./!!;
  874. $link="$from/$link" if length $from;
  875. }
  876. my $links = $IkiWiki::links{$page} or return undef;
  877. return 0 unless @$links;
  878. my $bestlink = IkiWiki::bestlink($from, $link);
  879. return 0 unless length $bestlink;
  880. foreach my $p (@$links) {
  881. return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
  882. }
  883. return 0;
  884. } #}}}
  885. sub match_backlink ($$$) { #{{{
  886. match_link($_[1], $_[0], $_[3]);
  887. } #}}}
  888. sub match_created_before ($$$) { #{{{
  889. my $page=shift;
  890. my $testpage=shift;
  891. if (exists $IkiWiki::pagectime{$testpage}) {
  892. return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
  893. }
  894. else {
  895. return 0;
  896. }
  897. } #}}}
  898. sub match_created_after ($$$) { #{{{
  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_creation_day ($$$) { #{{{
  909. return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
  910. } #}}}
  911. sub match_creation_month ($$$) { #{{{
  912. return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
  913. } #}}}
  914. sub match_creation_year ($$$) { #{{{
  915. return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
  916. } #}}}
  917. 1