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