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