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