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