summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: edbec77d62ed55f977f97c6f8b476d06c65c6676 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use URI::Escape q{uri_escape_utf8};
  8. use POSIX;
  9. use Storable;
  10. use open qw{:utf8 :std};
  11. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  12. %pagestate %renderedfiles %oldrenderedfiles %pagesources
  13. %destsources %depends %hooks %forcerebuild $gettext_obj};
  14. use Exporter q{import};
  15. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  16. bestlink htmllink readfile writefile pagetype srcfile pagename
  17. displaytime will_render gettext urlto targetpage
  18. add_underlay
  19. %config %links %pagestate %renderedfiles
  20. %pagesources %destsources);
  21. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  22. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  23. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  24. # Optimisation.
  25. use Memoize;
  26. memoize("abs2rel");
  27. memoize("pagespec_translate");
  28. memoize("file_pruned");
  29. sub getsetup () { #{{{
  30. wikiname => {
  31. type => "string",
  32. default => "wiki",
  33. description => "name of the wiki",
  34. safe => 1,
  35. rebuild => 1,
  36. },
  37. srcdir => {
  38. type => "string",
  39. default => undef,
  40. example => "$ENV{HOME}/wiki",
  41. description => "where the source of the wiki is located",
  42. safe => 0, # path
  43. rebuild => 1,
  44. },
  45. destdir => {
  46. type => "string",
  47. default => undef,
  48. example => "/var/www/wiki",
  49. description => "where to build the wiki",
  50. safe => 0, # path
  51. rebuild => 1,
  52. },
  53. adminuser => {
  54. type => "string",
  55. default => [],
  56. description => "user names of wiki admins",
  57. safe => 1,
  58. rebuild => 0,
  59. },
  60. adminemail => {
  61. type => "string",
  62. default => undef,
  63. example => 'me@example.com',
  64. description => "contact email for wiki",
  65. safe => 1,
  66. rebuild => 0,
  67. },
  68. url => {
  69. type => "string",
  70. default => '',
  71. example => "http://example.com/wiki",
  72. description => "base url to the wiki",
  73. safe => 1,
  74. rebuild => 1,
  75. },
  76. cgiurl => {
  77. type => "string",
  78. default => '',
  79. examples => "http://example.com/wiki/ikiwiki.cgi",
  80. description => "url to the ikiwiki.cgi",
  81. safe => 1,
  82. rebuild => 1,
  83. },
  84. rcs => {
  85. type => "string",
  86. default => '',
  87. description => "rcs backend to use",
  88. safe => 0, # don't allow overriding
  89. rebuild => 0,
  90. },
  91. historyurl => {
  92. type => "string",
  93. # TODO should be set per-rcs to allow different
  94. # examples and descriptions
  95. default => '',
  96. example => "XXX",
  97. description => "XXX",
  98. safe => 1,
  99. rebuild => 1,
  100. },
  101. diffurl => {
  102. type => "string",
  103. # TODO ditto above
  104. default => '',
  105. example => "XXX",
  106. description => "XXX",
  107. safe => 1,
  108. rebuild => 1,
  109. },
  110. discussion => {
  111. type => "boolean",
  112. default => 1,
  113. description => "enable Discussion pages?",
  114. safe => 1,
  115. rebuild => 1,
  116. },
  117. svnpath => {
  118. # TODO move
  119. type => "string",
  120. default => "trunk",
  121. description => "path inside svn repo where wiki is located",
  122. safe => 0, # could expose/overwrite data
  123. rebuild => 0,
  124. },
  125. gitorigin_branch => {
  126. type => "string",
  127. default => "origin",
  128. description => "the git origin to pull from",
  129. safe => 0, # paranoia
  130. rebuild => 0,
  131. },
  132. gitmaster_branch => {
  133. type => "string",
  134. default => "master",
  135. description => "the git master branch",
  136. safe => 0, # paranoia
  137. rebuild => 0,
  138. },
  139. wrappers => {
  140. type => "string",
  141. default => undef,
  142. description => "definitions of wrappers to generate",
  143. safe => 0,
  144. rebuild => 0,
  145. },
  146. wrapper => {
  147. type => "internal",
  148. default => undef,
  149. description => "wrapper filename",
  150. safe => 0,
  151. rebuild => 0,
  152. },
  153. wrappermode => {
  154. type => "internal",
  155. default => undef,
  156. description => "mode of wrapper file",
  157. safe => 0,
  158. rebuild => 0,
  159. },
  160. templatedir => {
  161. type => "string",
  162. default => "$installdir/share/ikiwiki/templates",
  163. description => "location of template files",
  164. safe => 0, # path
  165. rebuild => 1,
  166. },
  167. underlaydir => {
  168. type => "string",
  169. default => "$installdir/share/ikiwiki/basewiki",
  170. description => "base wiki source location",
  171. safe => 0, # path
  172. rebuild => 0,
  173. },
  174. underlaydirs => {
  175. type => "internal",
  176. default => [],
  177. description => "additional underlays to use",
  178. safe => 0,
  179. rebuild => 0,
  180. },
  181. verbose => {
  182. type => "boolean",
  183. default => 0,
  184. description => "display verbose messages when building?",
  185. safe => 1,
  186. rebuild => 0,
  187. },
  188. syslog => {
  189. type => "boolean",
  190. default => 0,
  191. description => "log to syslog?",
  192. safe => 1,
  193. rebuild => 0,
  194. },
  195. usedirs => {
  196. type => "boolean",
  197. default => 1,
  198. description => "create output files named page/index.html?",
  199. safe => 0, # changing requires manual transition
  200. rebuild => 1,
  201. },
  202. prefix_directives => {
  203. type => "boolean",
  204. default => 0,
  205. description => "use '!'-prefixed preprocessor directives?",
  206. safe => 0, # changing requires manual transition
  207. rebuild => 1,
  208. },
  209. default_pageext => {
  210. type => "string",
  211. default => "mdwn",
  212. description => "extension to use for new pages",
  213. safe => 0, # not sanitized
  214. rebuild => 0,
  215. },
  216. htmlext => {
  217. type => "string",
  218. default => "html",
  219. description => "extension to use for html files",
  220. safe => 0, # not sanitized
  221. rebuild => 1,
  222. },
  223. timeformat => {
  224. type => "string",
  225. default => '%c',
  226. description => "strftime format string to display date",
  227. safe => 1,
  228. rebuild => 1,
  229. },
  230. locale => {
  231. type => "string",
  232. default => undef,
  233. example => "en_US.UTF-8",
  234. description => "UTF-8 locale to use",
  235. safe => 0,
  236. rebuild => 1,
  237. },
  238. sslcookie => {
  239. type => "boolean",
  240. default => 0,
  241. description => "only send cookies over SSL connections?",
  242. safe => 1,
  243. rebuild => 0,
  244. },
  245. userdir => {
  246. type => "string",
  247. default => "",
  248. example => "users",
  249. description => "put user pages below specified page",
  250. safe => 1,
  251. rebuild => 1,
  252. },
  253. numbacklinks => {
  254. type => "integer",
  255. default => 10,
  256. description => "how many backlinks to show before hiding excess (0 to show all)",
  257. safe => 1,
  258. rebuild => 1,
  259. },
  260. hardlink => {
  261. type => "boolean",
  262. default => 0,
  263. description => "attempt to hardlink source files? (optimisation for large files)",
  264. safe => 0, # paranoia
  265. rebuild => 0,
  266. },
  267. exclude => {
  268. type => "string",
  269. default => undef,
  270. example => '\.wav$',
  271. description => "regexp of source files to ignore",
  272. safe => 0, # regexp
  273. rebuild => 1,
  274. },
  275. wiki_file_prune_regexps => {
  276. type => "internal",
  277. default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
  278. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  279. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  280. qr/(^|\/)_MTN\//,
  281. qr/\.dpkg-tmp$/],
  282. description => "regexps of source files to ignore",
  283. safe => 0,
  284. rebuild => 1,
  285. },
  286. wiki_file_regexp => {
  287. type => "internal",
  288. default => qr/(^[-[:alnum:]_.:\/+]+$)/,
  289. description => "regexp of legal source files",
  290. safe => 0,
  291. rebuild => 1,
  292. },
  293. web_commit_regexp => {
  294. type => "internal",
  295. default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
  296. description => "regexp to parse web commits from logs",
  297. safe => 0,
  298. rebuild => 0,
  299. },
  300. cgi => {
  301. type => "internal",
  302. default => 0,
  303. description => "run as a cgi",
  304. safe => 0,
  305. rebuild => 0,
  306. },
  307. cgi_disable_uploads => {
  308. type => "internal",
  309. default => 1,
  310. description => "whether CGI should accept file uploads",
  311. safe => 0,
  312. rebuild => 0,
  313. },
  314. post_commit => {
  315. type => "internal",
  316. default => 0,
  317. description => "run as a post-commit hook",
  318. safe => 0,
  319. rebuild => 0,
  320. },
  321. rebuild => {
  322. type => "internal",
  323. default => 0,
  324. description => "running in rebuild mode",
  325. safe => 0,
  326. rebuild => 0,
  327. },
  328. refresh => {
  329. type => "internal",
  330. default => 0,
  331. description => "running in refresh mode",
  332. safe => 0,
  333. rebuild => 0,
  334. },
  335. getctime => {
  336. type => "internal",
  337. default => 0,
  338. description => "running in getctime mode",
  339. safe => 0,
  340. rebuild => 0,
  341. },
  342. w3mmode => {
  343. type => "internal",
  344. default => 0,
  345. description => "running in w3mmode",
  346. safe => 0,
  347. rebuild => 0,
  348. },
  349. setup => {
  350. type => "internal",
  351. default => undef,
  352. description => "setup file to read",
  353. safe => 0,
  354. rebuild => 0,
  355. },
  356. default_plugins => {
  357. type => "internal",
  358. default => [qw{mdwn link inline htmlscrubber passwordauth
  359. openid signinedit lockedit conditional
  360. recentchanges parentlinks}],
  361. description => "plugins to enable by default",
  362. safe => 1,
  363. rebuild => 1,
  364. },
  365. add_plugins => {
  366. type => "string",
  367. default => [],
  368. description => "plugins to add to the default configuration",
  369. safe => 1,
  370. rebuild => 1,
  371. },
  372. disable_plugins => {
  373. type => "string",
  374. default => [],
  375. description => "plugins to disable",
  376. safe => 1,
  377. rebuild => 1,
  378. },
  379. libdir => {
  380. type => "internal",
  381. default => undef,
  382. example => "$ENV{HOME}/.ikiwiki/",
  383. description => "extra library and plugin directory",
  384. safe => 0,
  385. rebuild => 0,
  386. },
  387. } #}}}
  388. sub defaultconfig () { #{{{
  389. my %s=getsetup();
  390. my @ret;
  391. foreach my $key (keys %s) {
  392. push @ret, $key, $s{$key}->{default};
  393. }
  394. use Data::Dumper;
  395. return @ret;
  396. } #}}}
  397. sub checkconfig () { #{{{
  398. # locale stuff; avoid LC_ALL since it overrides everything
  399. if (defined $ENV{LC_ALL}) {
  400. $ENV{LANG} = $ENV{LC_ALL};
  401. delete $ENV{LC_ALL};
  402. }
  403. if (defined $config{locale}) {
  404. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  405. $ENV{LANG}=$config{locale};
  406. $gettext_obj=undef;
  407. }
  408. }
  409. if (ref $config{ENV} eq 'HASH') {
  410. foreach my $val (keys %{$config{ENV}}) {
  411. $ENV{$val}=$config{ENV}{$val};
  412. }
  413. }
  414. if ($config{w3mmode}) {
  415. eval q{use Cwd q{abs_path}};
  416. error($@) if $@;
  417. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  418. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  419. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  420. unless $config{cgiurl} =~ m!file:///!;
  421. $config{url}="file://".$config{destdir};
  422. }
  423. if ($config{cgi} && ! length $config{url}) {
  424. error(gettext("Must specify url to wiki with --url when using --cgi"));
  425. }
  426. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  427. unless exists $config{wikistatedir};
  428. if ($config{rcs}) {
  429. eval qq{use IkiWiki::Rcs::$config{rcs}};
  430. if ($@) {
  431. error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
  432. }
  433. }
  434. else {
  435. require IkiWiki::Rcs::Stub;
  436. }
  437. if (exists $config{umask}) {
  438. umask(possibly_foolish_untaint($config{umask}));
  439. }
  440. run_hooks(checkconfig => sub { shift->() });
  441. return 1;
  442. } #}}}
  443. sub loadplugins () { #{{{
  444. if (defined $config{libdir}) {
  445. unshift @INC, possibly_foolish_untaint($config{libdir});
  446. }
  447. loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
  448. run_hooks(getopt => sub { shift->() });
  449. if (grep /^-/, @ARGV) {
  450. print STDERR "Unknown option: $_\n"
  451. foreach grep /^-/, @ARGV;
  452. usage();
  453. }
  454. return 1;
  455. } #}}}
  456. sub loadplugin ($) { #{{{
  457. my $plugin=shift;
  458. return if grep { $_ eq $plugin} @{$config{disable_plugins}};
  459. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  460. "$installdir/lib/ikiwiki") {
  461. if (defined $dir && -x "$dir/plugins/$plugin") {
  462. require IkiWiki::Plugin::external;
  463. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  464. return 1;
  465. }
  466. }
  467. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  468. eval qq{use $mod};
  469. if ($@) {
  470. error("Failed to load plugin $mod: $@");
  471. }
  472. return 1;
  473. } #}}}
  474. sub error ($;$) { #{{{
  475. my $message=shift;
  476. my $cleaner=shift;
  477. log_message('err' => $message) if $config{syslog};
  478. if (defined $cleaner) {
  479. $cleaner->();
  480. }
  481. die $message."\n";
  482. } #}}}
  483. sub debug ($) { #{{{
  484. return unless $config{verbose};
  485. return log_message(debug => @_);
  486. } #}}}
  487. my $log_open=0;
  488. sub log_message ($$) { #{{{
  489. my $type=shift;
  490. if ($config{syslog}) {
  491. require Sys::Syslog;
  492. if (! $log_open) {
  493. Sys::Syslog::setlogsock('unix');
  494. Sys::Syslog::openlog('ikiwiki', '', 'user');
  495. $log_open=1;
  496. }
  497. return eval {
  498. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  499. };
  500. }
  501. elsif (! $config{cgi}) {
  502. return print "@_\n";
  503. }
  504. else {
  505. return print STDERR "@_\n";
  506. }
  507. } #}}}
  508. sub possibly_foolish_untaint ($) { #{{{
  509. my $tainted=shift;
  510. my ($untainted)=$tainted=~/(.*)/s;
  511. return $untainted;
  512. } #}}}
  513. sub basename ($) { #{{{
  514. my $file=shift;
  515. $file=~s!.*/+!!;
  516. return $file;
  517. } #}}}
  518. sub dirname ($) { #{{{
  519. my $file=shift;
  520. $file=~s!/*[^/]+$!!;
  521. return $file;
  522. } #}}}
  523. sub pagetype ($) { #{{{
  524. my $page=shift;
  525. if ($page =~ /\.([^.]+)$/) {
  526. return $1 if exists $hooks{htmlize}{$1};
  527. }
  528. return;
  529. } #}}}
  530. sub isinternal ($) { #{{{
  531. my $page=shift;
  532. return exists $pagesources{$page} &&
  533. $pagesources{$page} =~ /\._([^.]+)$/;
  534. } #}}}
  535. sub pagename ($) { #{{{
  536. my $file=shift;
  537. my $type=pagetype($file);
  538. my $page=$file;
  539. $page=~s/\Q.$type\E*$// if defined $type;
  540. return $page;
  541. } #}}}
  542. sub targetpage ($$) { #{{{
  543. my $page=shift;
  544. my $ext=shift;
  545. if (! $config{usedirs} || $page =~ /^index$/ ) {
  546. return $page.".".$ext;
  547. } else {
  548. return $page."/index.".$ext;
  549. }
  550. } #}}}
  551. sub htmlpage ($) { #{{{
  552. my $page=shift;
  553. return targetpage($page, $config{htmlext});
  554. } #}}}
  555. sub srcfile_stat { #{{{
  556. my $file=shift;
  557. my $nothrow=shift;
  558. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  559. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  560. return "$dir/$file", stat(_) if -e "$dir/$file";
  561. }
  562. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  563. return;
  564. } #}}}
  565. sub srcfile ($;$) { #{{{
  566. return (srcfile_stat(@_))[0];
  567. } #}}}
  568. sub add_underlay ($) { #{{{
  569. my $dir=shift;
  570. if ($dir=~/^\//) {
  571. unshift @{$config{underlaydirs}}, $dir;
  572. }
  573. else {
  574. unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
  575. }
  576. return 1;
  577. } #}}}
  578. sub readfile ($;$$) { #{{{
  579. my $file=shift;
  580. my $binary=shift;
  581. my $wantfd=shift;
  582. if (-l $file) {
  583. error("cannot read a symlink ($file)");
  584. }
  585. local $/=undef;
  586. open (my $in, "<", $file) || error("failed to read $file: $!");
  587. binmode($in) if ($binary);
  588. return \*$in if $wantfd;
  589. my $ret=<$in>;
  590. close $in || error("failed to read $file: $!");
  591. return $ret;
  592. } #}}}
  593. sub prep_writefile ($$) { #{{{
  594. my $file=shift;
  595. my $destdir=shift;
  596. my $test=$file;
  597. while (length $test) {
  598. if (-l "$destdir/$test") {
  599. error("cannot write to a symlink ($test)");
  600. }
  601. $test=dirname($test);
  602. }
  603. my $dir=dirname("$destdir/$file");
  604. if (! -d $dir) {
  605. my $d="";
  606. foreach my $s (split(m!/+!, $dir)) {
  607. $d.="$s/";
  608. if (! -d $d) {
  609. mkdir($d) || error("failed to create directory $d: $!");
  610. }
  611. }
  612. }
  613. return 1;
  614. } #}}}
  615. sub writefile ($$$;$$) { #{{{
  616. my $file=shift; # can include subdirs
  617. my $destdir=shift; # directory to put file in
  618. my $content=shift;
  619. my $binary=shift;
  620. my $writer=shift;
  621. prep_writefile($file, $destdir);
  622. my $newfile="$destdir/$file.ikiwiki-new";
  623. if (-l $newfile) {
  624. error("cannot write to a symlink ($newfile)");
  625. }
  626. my $cleanup = sub { unlink($newfile) };
  627. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  628. binmode($out) if ($binary);
  629. if ($writer) {
  630. $writer->(\*$out, $cleanup);
  631. }
  632. else {
  633. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  634. }
  635. close $out || error("failed saving $newfile: $!", $cleanup);
  636. rename($newfile, "$destdir/$file") ||
  637. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  638. return 1;
  639. } #}}}
  640. my %cleared;
  641. sub will_render ($$;$) { #{{{
  642. my $page=shift;
  643. my $dest=shift;
  644. my $clear=shift;
  645. # Important security check.
  646. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  647. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
  648. error("$config{destdir}/$dest independently created, not overwriting with version from $page");
  649. }
  650. if (! $clear || $cleared{$page}) {
  651. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  652. }
  653. else {
  654. foreach my $old (@{$renderedfiles{$page}}) {
  655. delete $destsources{$old};
  656. }
  657. $renderedfiles{$page}=[$dest];
  658. $cleared{$page}=1;
  659. }
  660. $destsources{$dest}=$page;
  661. return 1;
  662. } #}}}
  663. sub bestlink ($$) { #{{{
  664. my $page=shift;
  665. my $link=shift;
  666. my $cwd=$page;
  667. if ($link=~s/^\/+//) {
  668. # absolute links
  669. $cwd="";
  670. }
  671. $link=~s/\/$//;
  672. do {
  673. my $l=$cwd;
  674. $l.="/" if length $l;
  675. $l.=$link;
  676. if (exists $links{$l}) {
  677. return $l;
  678. }
  679. elsif (exists $pagecase{lc $l}) {
  680. return $pagecase{lc $l};
  681. }
  682. } while $cwd=~s!/?[^/]+$!!;
  683. if (length $config{userdir}) {
  684. my $l = "$config{userdir}/".lc($link);
  685. if (exists $links{$l}) {
  686. return $l;
  687. }
  688. elsif (exists $pagecase{lc $l}) {
  689. return $pagecase{lc $l};
  690. }
  691. }
  692. #print STDERR "warning: page $page, broken link: $link\n";
  693. return "";
  694. } #}}}
  695. sub isinlinableimage ($) { #{{{
  696. my $file=shift;
  697. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  698. } #}}}
  699. sub pagetitle ($;$) { #{{{
  700. my $page=shift;
  701. my $unescaped=shift;
  702. if ($unescaped) {
  703. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  704. }
  705. else {
  706. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  707. }
  708. return $page;
  709. } #}}}
  710. sub titlepage ($) { #{{{
  711. my $title=shift;
  712. $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  713. return $title;
  714. } #}}}
  715. sub linkpage ($) { #{{{
  716. my $link=shift;
  717. $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  718. return $link;
  719. } #}}}
  720. sub cgiurl (@) { #{{{
  721. my %params=@_;
  722. return $config{cgiurl}."?".
  723. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  724. } #}}}
  725. sub baseurl (;$) { #{{{
  726. my $page=shift;
  727. return "$config{url}/" if ! defined $page;
  728. $page=htmlpage($page);
  729. $page=~s/[^\/]+$//;
  730. $page=~s/[^\/]+\//..\//g;
  731. return $page;
  732. } #}}}
  733. sub abs2rel ($$) { #{{{
  734. # Work around very innefficient behavior in File::Spec if abs2rel
  735. # is passed two relative paths. It's much faster if paths are
  736. # absolute! (Debian bug #376658; fixed in debian unstable now)
  737. my $path="/".shift;
  738. my $base="/".shift;
  739. require File::Spec;
  740. my $ret=File::Spec->abs2rel($path, $base);
  741. $ret=~s/^// if defined $ret;
  742. return $ret;
  743. } #}}}
  744. sub displaytime ($;$) { #{{{
  745. my $time=shift;
  746. my $format=shift;
  747. if (! defined $format) {
  748. $format=$config{timeformat};
  749. }
  750. # strftime doesn't know about encodings, so make sure
  751. # its output is properly treated as utf8
  752. return decode_utf8(POSIX::strftime($format, localtime($time)));
  753. } #}}}
  754. sub beautify_urlpath ($) { #{{{
  755. my $url=shift;
  756. if ($config{usedirs}) {
  757. $url =~ s!/index.$config{htmlext}$!/!;
  758. }
  759. # Ensure url is not an empty link, and
  760. # if it's relative, make that explicit to avoid colon confusion.
  761. if ($url !~ /^\//) {
  762. $url="./$url";
  763. }
  764. return $url;
  765. } #}}}
  766. sub urlto ($$;$) { #{{{
  767. my $to=shift;
  768. my $from=shift;
  769. my $absolute=shift;
  770. if (! length $to) {
  771. return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
  772. }
  773. if (! $destsources{$to}) {
  774. $to=htmlpage($to);
  775. }
  776. if ($absolute) {
  777. return $config{url}.beautify_urlpath("/".$to);
  778. }
  779. my $link = abs2rel($to, dirname(htmlpage($from)));
  780. return beautify_urlpath($link);
  781. } #}}}
  782. sub htmllink ($$$;@) { #{{{
  783. my $lpage=shift; # the page doing the linking
  784. my $page=shift; # the page that will contain the link (different for inline)
  785. my $link=shift;
  786. my %opts=@_;
  787. $link=~s/\/$//;
  788. my $bestlink;
  789. if (! $opts{forcesubpage}) {
  790. $bestlink=bestlink($lpage, $link);
  791. }
  792. else {
  793. $bestlink="$lpage/".lc($link);
  794. }
  795. my $linktext;
  796. if (defined $opts{linktext}) {
  797. $linktext=$opts{linktext};
  798. }
  799. else {
  800. $linktext=pagetitle(basename($link));
  801. }
  802. return "<span class=\"selflink\">$linktext</span>"
  803. if length $bestlink && $page eq $bestlink &&
  804. ! defined $opts{anchor};
  805. if (! $destsources{$bestlink}) {
  806. $bestlink=htmlpage($bestlink);
  807. if (! $destsources{$bestlink}) {
  808. return $linktext unless length $config{cgiurl};
  809. return "<span class=\"createlink\"><a href=\"".
  810. cgiurl(
  811. do => "create",
  812. page => lc($link),
  813. from => $lpage
  814. ).
  815. "\" rel=\"nofollow\">?</a>$linktext</span>"
  816. }
  817. }
  818. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  819. $bestlink=beautify_urlpath($bestlink);
  820. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  821. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  822. }
  823. if (defined $opts{anchor}) {
  824. $bestlink.="#".$opts{anchor};
  825. }
  826. my @attrs;
  827. if (defined $opts{rel}) {
  828. push @attrs, ' rel="'.$opts{rel}.'"';
  829. }
  830. if (defined $opts{class}) {
  831. push @attrs, ' class="'.$opts{class}.'"';
  832. }
  833. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  834. } #}}}
  835. sub userlink ($) { #{{{
  836. my $user=shift;
  837. my $oiduser=eval { openiduser($user) };
  838. if (defined $oiduser) {
  839. return "<a href=\"$user\">$oiduser</a>";
  840. }
  841. else {
  842. eval q{use CGI 'escapeHTML'};
  843. error($@) if $@;
  844. return htmllink("", "", escapeHTML(
  845. length $config{userdir} ? $config{userdir}."/".$user : $user
  846. ), noimageinline => 1);
  847. }
  848. } #}}}
  849. sub htmlize ($$$$) { #{{{
  850. my $page=shift;
  851. my $destpage=shift;
  852. my $type=shift;
  853. my $content=shift;
  854. my $oneline = $content !~ /\n/;
  855. if (exists $hooks{htmlize}{$type}) {
  856. $content=$hooks{htmlize}{$type}{call}->(
  857. page => $page,
  858. content => $content,
  859. );
  860. }
  861. else {
  862. error("htmlization of $type not supported");
  863. }
  864. run_hooks(sanitize => sub {
  865. $content=shift->(
  866. page => $page,
  867. destpage => $destpage,
  868. content => $content,
  869. );
  870. });
  871. if ($oneline) {
  872. # hack to get rid of enclosing junk added by markdown
  873. # and other htmlizers
  874. $content=~s/^<p>//i;
  875. $content=~s/<\/p>$//i;
  876. chomp $content;
  877. }
  878. return $content;
  879. } #}}}
  880. sub linkify ($$$) { #{{{
  881. my $page=shift;
  882. my $destpage=shift;
  883. my $content=shift;
  884. run_hooks(linkify => sub {
  885. $content=shift->(
  886. page => $page,
  887. destpage => $destpage,
  888. content => $content,
  889. );
  890. });
  891. return $content;
  892. } #}}}
  893. our %preprocessing;
  894. our $preprocess_preview=0;
  895. sub preprocess ($$$;$$) { #{{{
  896. my $page=shift; # the page the data comes from
  897. my $destpage=shift; # the page the data will appear in (different for inline)
  898. my $content=shift;
  899. my $scan=shift;
  900. my $preview=shift;
  901. # Using local because it needs to be set within any nested calls
  902. # of this function.
  903. local $preprocess_preview=$preview if defined $preview;
  904. my $handle=sub {
  905. my $escape=shift;
  906. my $prefix=shift;
  907. my $command=shift;
  908. my $params=shift;
  909. if (length $escape) {
  910. return "[[$prefix$command $params]]";
  911. }
  912. elsif (exists $hooks{preprocess}{$command}) {
  913. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  914. # Note: preserve order of params, some plugins may
  915. # consider it significant.
  916. my @params;
  917. while ($params =~ m{
  918. (?:([-\w]+)=)? # 1: named parameter key?
  919. (?:
  920. """(.*?)""" # 2: triple-quoted value
  921. |
  922. "([^"]+)" # 3: single-quoted value
  923. |
  924. (\S+) # 4: unquoted value
  925. )
  926. (?:\s+|$) # delimiter to next param
  927. }sgx) {
  928. my $key=$1;
  929. my $val;
  930. if (defined $2) {
  931. $val=$2;
  932. $val=~s/\r\n/\n/mg;
  933. $val=~s/^\n+//g;
  934. $val=~s/\n+$//g;
  935. }
  936. elsif (defined $3) {
  937. $val=$3;
  938. }
  939. elsif (defined $4) {
  940. $val=$4;
  941. }
  942. if (defined $key) {
  943. push @params, $key, $val;
  944. }
  945. else {
  946. push @params, $val, '';
  947. }
  948. }
  949. if ($preprocessing{$page}++ > 3) {
  950. # Avoid loops of preprocessed pages preprocessing
  951. # other pages that preprocess them, etc.
  952. #translators: The first parameter is a
  953. #translators: preprocessor directive name,
  954. #translators: the second a page name, the
  955. #translators: third a number.
  956. return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
  957. $command, $page, $preprocessing{$page}).
  958. "]]";
  959. }
  960. my $ret;
  961. if (! $scan) {
  962. $ret=eval {
  963. $hooks{preprocess}{$command}{call}->(
  964. @params,
  965. page => $page,
  966. destpage => $destpage,
  967. preview => $preprocess_preview,
  968. );
  969. };
  970. if ($@) {
  971. chomp $@;
  972. $ret="[[!$command <span class=\"error\">".
  973. gettext("Error").": $@"."</span>]]";
  974. }
  975. }
  976. else {
  977. # use void context during scan pass
  978. eval {
  979. $hooks{preprocess}{$command}{call}->(
  980. @params,
  981. page => $page,
  982. destpage => $destpage,
  983. preview => $preprocess_preview,
  984. );
  985. };
  986. $ret="";
  987. }
  988. $preprocessing{$page}--;
  989. return $ret;
  990. }
  991. else {
  992. return "[[$prefix$command $params]]";
  993. }
  994. };
  995. my $regex;
  996. if ($config{prefix_directives}) {
  997. $regex = qr{
  998. (\\?) # 1: escape?
  999. \[\[(!) # directive open; 2: prefix
  1000. ([-\w]+) # 3: command
  1001. ( # 4: the parameters..
  1002. \s+ # Must have space if parameters present
  1003. (?:
  1004. (?:[-\w]+=)? # named parameter key?
  1005. (?:
  1006. """.*?""" # triple-quoted value
  1007. |
  1008. "[^"]+" # single-quoted value
  1009. |
  1010. [^\s\]]+ # unquoted value
  1011. )
  1012. \s* # whitespace or end
  1013. # of directive
  1014. )
  1015. *)? # 0 or more parameters
  1016. \]\] # directive closed
  1017. }sx;
  1018. }
  1019. else {
  1020. $regex = qr{
  1021. (\\?) # 1: escape?
  1022. \[\[(!?) # directive open; 2: optional prefix
  1023. ([-\w]+) # 3: command
  1024. \s+
  1025. ( # 4: the parameters..
  1026. (?:
  1027. (?:[-\w]+=)? # named parameter key?
  1028. (?:
  1029. """.*?""" # triple-quoted value
  1030. |
  1031. "[^"]+" # single-quoted value
  1032. |
  1033. [^\s\]]+ # unquoted value
  1034. )
  1035. \s* # whitespace or end
  1036. # of directive
  1037. )
  1038. *) # 0 or more parameters
  1039. \]\] # directive closed
  1040. }sx;
  1041. }
  1042. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1043. return $content;
  1044. } #}}}
  1045. sub filter ($$$) { #{{{
  1046. my $page=shift;
  1047. my $destpage=shift;
  1048. my $content=shift;
  1049. run_hooks(filter => sub {
  1050. $content=shift->(page => $page, destpage => $destpage,
  1051. content => $content);
  1052. });
  1053. return $content;
  1054. } #}}}
  1055. sub indexlink () { #{{{
  1056. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  1057. } #}}}
  1058. my $wikilock;
  1059. sub lockwiki (;$) { #{{{
  1060. my $wait=@_ ? shift : 1;
  1061. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1062. # run issues. The lock will be dropped on program exit.
  1063. if (! -d $config{wikistatedir}) {
  1064. mkdir($config{wikistatedir});
  1065. }
  1066. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1067. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1068. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  1069. if ($wait) {
  1070. debug("wiki seems to be locked, waiting for lock");
  1071. my $wait=600; # arbitrary, but don't hang forever to
  1072. # prevent process pileup
  1073. for (1..$wait) {
  1074. return if flock($wikilock, 2 | 4);
  1075. sleep 1;
  1076. }
  1077. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  1078. }
  1079. else {
  1080. return 0;
  1081. }
  1082. }
  1083. return 1;
  1084. } #}}}
  1085. sub unlockwiki () { #{{{
  1086. return close($wikilock) if $wikilock;
  1087. return;
  1088. } #}}}
  1089. my $commitlock;
  1090. sub commit_hook_enabled () { #{{{
  1091. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1092. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1093. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1094. close($commitlock) || error("failed closing commitlock: $!");
  1095. return 0;
  1096. }
  1097. close($commitlock) || error("failed closing commitlock: $!");
  1098. return 1;
  1099. } #}}}
  1100. sub disable_commit_hook () { #{{{
  1101. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1102. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1103. if (! flock($commitlock, 2)) { # LOCK_EX
  1104. error("failed to get commit lock");
  1105. }
  1106. return 1;
  1107. } #}}}
  1108. sub enable_commit_hook () { #{{{
  1109. return close($commitlock) if $commitlock;
  1110. return;
  1111. } #}}}
  1112. sub loadindex () { #{{{
  1113. %oldrenderedfiles=%pagectime=();
  1114. if (! $config{rebuild}) {
  1115. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1116. %destsources=%renderedfiles=%pagecase=%pagestate=();
  1117. }
  1118. my $in;
  1119. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1120. if (-e "$config{wikistatedir}/index") {
  1121. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1122. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1123. }
  1124. else {
  1125. return;
  1126. }
  1127. }
  1128. my $ret=Storable::fd_retrieve($in);
  1129. if (! defined $ret) {
  1130. return 0;
  1131. }
  1132. my %index=%$ret;
  1133. foreach my $src (keys %index) {
  1134. my %d=%{$index{$src}};
  1135. my $page=pagename($src);
  1136. $pagectime{$page}=$d{ctime};
  1137. if (! $config{rebuild}) {
  1138. $pagesources{$page}=$src;
  1139. $pagemtime{$page}=$d{mtime};
  1140. $renderedfiles{$page}=$d{dest};
  1141. if (exists $d{links} && ref $d{links}) {
  1142. $links{$page}=$d{links};
  1143. $oldlinks{$page}=[@{$d{links}}];
  1144. }
  1145. if (exists $d{depends}) {
  1146. $depends{$page}=$d{depends};
  1147. }
  1148. if (exists $d{state}) {
  1149. $pagestate{$page}=$d{state};
  1150. }
  1151. }
  1152. $oldrenderedfiles{$page}=[@{$d{dest}}];
  1153. }
  1154. foreach my $page (keys %pagesources) {
  1155. $pagecase{lc $page}=$page;
  1156. }
  1157. foreach my $page (keys %renderedfiles) {
  1158. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1159. }
  1160. return close($in);
  1161. } #}}}
  1162. sub saveindex () { #{{{
  1163. run_hooks(savestate => sub { shift->() });
  1164. my %hookids;
  1165. foreach my $type (keys %hooks) {
  1166. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1167. }
  1168. my @hookids=keys %hookids;
  1169. if (! -d $config{wikistatedir}) {
  1170. mkdir($config{wikistatedir});
  1171. }
  1172. my $newfile="$config{wikistatedir}/indexdb.new";
  1173. my $cleanup = sub { unlink($newfile) };
  1174. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1175. my %index;
  1176. foreach my $page (keys %pagemtime) {
  1177. next unless $pagemtime{$page};
  1178. my $src=$pagesources{$page};
  1179. $index{$src}={
  1180. ctime => $pagectime{$page},
  1181. mtime => $pagemtime{$page},
  1182. dest => $renderedfiles{$page},
  1183. links => $links{$page},
  1184. };
  1185. if (exists $depends{$page}) {
  1186. $index{$src}{depends} = $depends{$page};
  1187. }
  1188. if (exists $pagestate{$page}) {
  1189. foreach my $id (@hookids) {
  1190. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1191. $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1192. }
  1193. }
  1194. }
  1195. }
  1196. my $ret=Storable::nstore_fd(\%index, $out);
  1197. return if ! defined $ret || ! $ret;
  1198. close $out || error("failed saving to $newfile: $!", $cleanup);
  1199. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1200. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1201. return 1;
  1202. } #}}}
  1203. sub template_file ($) { #{{{
  1204. my $template=shift;
  1205. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1206. return "$dir/$template" if -e "$dir/$template";
  1207. }
  1208. return;
  1209. } #}}}
  1210. sub template_params (@) { #{{{
  1211. my $filename=template_file(shift);
  1212. if (! defined $filename) {
  1213. return if wantarray;
  1214. return "";
  1215. }
  1216. my @ret=(
  1217. filter => sub {
  1218. my $text_ref = shift;
  1219. ${$text_ref} = decode_utf8(${$text_ref});
  1220. },
  1221. filename => $filename,
  1222. loop_context_vars => 1,
  1223. die_on_bad_params => 0,
  1224. @_
  1225. );
  1226. return wantarray ? @ret : {@ret};
  1227. } #}}}
  1228. sub template ($;@) { #{{{
  1229. require HTML::Template;
  1230. return HTML::Template->new(template_params(@_));
  1231. } #}}}
  1232. sub misctemplate ($$;@) { #{{{
  1233. my $title=shift;
  1234. my $pagebody=shift;
  1235. my $template=template("misc.tmpl");
  1236. $template->param(
  1237. title => $title,
  1238. indexlink => indexlink(),
  1239. wikiname => $config{wikiname},
  1240. pagebody => $pagebody,
  1241. baseurl => baseurl(),
  1242. @_,
  1243. );
  1244. run_hooks(pagetemplate => sub {
  1245. shift->(page => "", destpage => "", template => $template);
  1246. });
  1247. return $template->output;
  1248. }#}}}
  1249. sub hook (@) { # {{{
  1250. my %param=@_;
  1251. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1252. error 'hook requires type, call, and id parameters';
  1253. }
  1254. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1255. $hooks{$param{type}}{$param{id}}=\%param;
  1256. return 1;
  1257. } # }}}
  1258. sub run_hooks ($$) { # {{{
  1259. # Calls the given sub for each hook of the given type,
  1260. # passing it the hook function to call.
  1261. my $type=shift;
  1262. my $sub=shift;
  1263. if (exists $hooks{$type}) {
  1264. my @deferred;
  1265. foreach my $id (keys %{$hooks{$type}}) {
  1266. if ($hooks{$type}{$id}{last}) {
  1267. push @deferred, $id;
  1268. next;
  1269. }
  1270. $sub->($hooks{$type}{$id}{call});
  1271. }
  1272. foreach my $id (@deferred) {
  1273. $sub->($hooks{$type}{$id}{call});
  1274. }
  1275. }
  1276. return 1;
  1277. } #}}}
  1278. sub globlist_to_pagespec ($) { #{{{
  1279. my @globlist=split(' ', shift);
  1280. my (@spec, @skip);
  1281. foreach my $glob (@globlist) {
  1282. if ($glob=~/^!(.*)/) {
  1283. push @skip, $glob;
  1284. }
  1285. else {
  1286. push @spec, $glob;
  1287. }
  1288. }
  1289. my $spec=join(' or ', @spec);
  1290. if (@skip) {
  1291. my $skip=join(' and ', @skip);
  1292. if (length $spec) {
  1293. $spec="$skip and ($spec)";
  1294. }
  1295. else {
  1296. $spec=$skip;
  1297. }
  1298. }
  1299. return $spec;
  1300. } #}}}
  1301. sub is_globlist ($) { #{{{
  1302. my $s=shift;
  1303. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  1304. } #}}}
  1305. sub safequote ($) { #{{{
  1306. my $s=shift;
  1307. $s=~s/[{}]//g;
  1308. return "q{$s}";
  1309. } #}}}
  1310. sub add_depends ($$) { #{{{
  1311. my $page=shift;
  1312. my $pagespec=shift;
  1313. return unless pagespec_valid($pagespec);
  1314. if (! exists $depends{$page}) {
  1315. $depends{$page}=$pagespec;
  1316. }
  1317. else {
  1318. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1319. }
  1320. return 1;
  1321. } # }}}
  1322. sub file_pruned ($$) { #{{{
  1323. require File::Spec;
  1324. my $file=File::Spec->canonpath(shift);
  1325. my $base=File::Spec->canonpath(shift);
  1326. $file =~ s#^\Q$base\E/+##;
  1327. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1328. return $file =~ m/$regexp/ && $file ne $base;
  1329. } #}}}
  1330. sub gettext { #{{{
  1331. # Only use gettext in the rare cases it's needed.
  1332. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1333. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1334. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1335. if (! $gettext_obj) {
  1336. $gettext_obj=eval q{
  1337. use Locale::gettext q{textdomain};
  1338. Locale::gettext->domain('ikiwiki')
  1339. };
  1340. if ($@) {
  1341. print STDERR "$@";
  1342. $gettext_obj=undef;
  1343. return shift;
  1344. }
  1345. }
  1346. return $gettext_obj->get(shift);
  1347. }
  1348. else {
  1349. return shift;
  1350. }
  1351. } #}}}
  1352. sub yesno ($) { #{{{
  1353. my $val=shift;
  1354. return (defined $val && lc($val) eq gettext("yes"));
  1355. } #}}}
  1356. sub pagespec_merge ($$) { #{{{
  1357. my $a=shift;
  1358. my $b=shift;
  1359. return $a if $a eq $b;
  1360. # Support for old-style GlobLists.
  1361. if (is_globlist($a)) {
  1362. $a=globlist_to_pagespec($a);
  1363. }
  1364. if (is_globlist($b)) {
  1365. $b=globlist_to_pagespec($b);
  1366. }
  1367. return "($a) or ($b)";
  1368. } #}}}
  1369. sub pagespec_translate ($) { #{{{
  1370. my $spec=shift;
  1371. # Support for old-style GlobLists.
  1372. if (is_globlist($spec)) {
  1373. $spec=globlist_to_pagespec($spec);
  1374. }
  1375. # Convert spec to perl code.
  1376. my $code="";
  1377. while ($spec=~m{
  1378. \s* # ignore whitespace
  1379. ( # 1: match a single word
  1380. \! # !
  1381. |
  1382. \( # (
  1383. |
  1384. \) # )
  1385. |
  1386. \w+\([^\)]*\) # command(params)
  1387. |
  1388. [^\s()]+ # any other text
  1389. )
  1390. \s* # ignore whitespace
  1391. }igx) {
  1392. my $word=$1;
  1393. if (lc $word eq 'and') {
  1394. $code.=' &&';
  1395. }
  1396. elsif (lc $word eq 'or') {
  1397. $code.=' ||';
  1398. }
  1399. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1400. $code.=' '.$word;
  1401. }
  1402. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1403. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1404. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1405. }
  1406. else {
  1407. $code.=' 0';
  1408. }
  1409. }
  1410. else {
  1411. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1412. }
  1413. }
  1414. if (! length $code) {
  1415. $code=0;
  1416. }
  1417. no warnings;
  1418. return eval 'sub { my $page=shift; '.$code.' }';
  1419. } #}}}
  1420. sub pagespec_match ($$;@) { #{{{
  1421. my $page=shift;
  1422. my $spec=shift;
  1423. my @params=@_;
  1424. # Backwards compatability with old calling convention.
  1425. if (@params == 1) {
  1426. unshift @params, 'location';
  1427. }
  1428. my $sub=pagespec_translate($spec);
  1429. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1430. return $sub->($page, @params);
  1431. } #}}}
  1432. sub pagespec_valid ($) { #{{{
  1433. my $spec=shift;
  1434. my $sub=pagespec_translate($spec);
  1435. return ! $@;
  1436. } #}}}
  1437. sub glob2re ($) { #{{{
  1438. my $re=quotemeta(shift);
  1439. $re=~s/\\\*/.*/g;
  1440. $re=~s/\\\?/./g;
  1441. return $re;
  1442. } #}}}
  1443. package IkiWiki::FailReason;
  1444. use overload ( #{{{
  1445. '""' => sub { ${$_[0]} },
  1446. '0+' => sub { 0 },
  1447. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1448. fallback => 1,
  1449. ); #}}}
  1450. sub new { #{{{
  1451. my $class = shift;
  1452. my $value = shift;
  1453. return bless \$value, $class;
  1454. } #}}}
  1455. package IkiWiki::SuccessReason;
  1456. use overload ( #{{{
  1457. '""' => sub { ${$_[0]} },
  1458. '0+' => sub { 1 },
  1459. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1460. fallback => 1,
  1461. ); #}}}
  1462. sub new { #{{{
  1463. my $class = shift;
  1464. my $value = shift;
  1465. return bless \$value, $class;
  1466. }; #}}}
  1467. package IkiWiki::PageSpec;
  1468. sub match_glob ($$;@) { #{{{
  1469. my $page=shift;
  1470. my $glob=shift;
  1471. my %params=@_;
  1472. my $from=exists $params{location} ? $params{location} : '';
  1473. # relative matching
  1474. if ($glob =~ m!^\./!) {
  1475. $from=~s#/?[^/]+$##;
  1476. $glob=~s#^\./##;
  1477. $glob="$from/$glob" if length $from;
  1478. }
  1479. my $regexp=IkiWiki::glob2re($glob);
  1480. if ($page=~/^$regexp$/i) {
  1481. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1482. return IkiWiki::SuccessReason->new("$glob matches $page");
  1483. }
  1484. else {
  1485. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1486. }
  1487. }
  1488. else {
  1489. return IkiWiki::FailReason->new("$glob does not match $page");
  1490. }
  1491. } #}}}
  1492. sub match_internal ($$;@) { #{{{
  1493. return match_glob($_[0], $_[1], @_, internal => 1)
  1494. } #}}}
  1495. sub match_link ($$;@) { #{{{
  1496. my $page=shift;
  1497. my $link=lc(shift);
  1498. my %params=@_;
  1499. my $from=exists $params{location} ? $params{location} : '';
  1500. # relative matching
  1501. if ($link =~ m!^\.! && defined $from) {
  1502. $from=~s#/?[^/]+$##;
  1503. $link=~s#^\./##;
  1504. $link="$from/$link" if length $from;
  1505. }
  1506. my $links = $IkiWiki::links{$page};
  1507. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1508. my $bestlink = IkiWiki::bestlink($from, $link);
  1509. foreach my $p (@{$links}) {
  1510. if (length $bestlink) {
  1511. return IkiWiki::SuccessReason->new("$page links to $link")
  1512. if $bestlink eq IkiWiki::bestlink($page, $p);
  1513. }
  1514. else {
  1515. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1516. if match_glob($p, $link, %params);
  1517. }
  1518. }
  1519. return IkiWiki::FailReason->new("$page does not link to $link");
  1520. } #}}}
  1521. sub match_backlink ($$;@) { #{{{
  1522. return match_link($_[1], $_[0], @_);
  1523. } #}}}
  1524. sub match_created_before ($$;@) { #{{{
  1525. my $page=shift;
  1526. my $testpage=shift;
  1527. if (exists $IkiWiki::pagectime{$testpage}) {
  1528. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1529. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1530. }
  1531. else {
  1532. return IkiWiki::FailReason->new("$page not created before $testpage");
  1533. }
  1534. }
  1535. else {
  1536. return IkiWiki::FailReason->new("$testpage has no ctime");
  1537. }
  1538. } #}}}
  1539. sub match_created_after ($$;@) { #{{{
  1540. my $page=shift;
  1541. my $testpage=shift;
  1542. if (exists $IkiWiki::pagectime{$testpage}) {
  1543. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1544. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1545. }
  1546. else {
  1547. return IkiWiki::FailReason->new("$page not created after $testpage");
  1548. }
  1549. }
  1550. else {
  1551. return IkiWiki::FailReason->new("$testpage has no ctime");
  1552. }
  1553. } #}}}
  1554. sub match_creation_day ($$;@) { #{{{
  1555. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1556. return IkiWiki::SuccessReason->new('creation_day matched');
  1557. }
  1558. else {
  1559. return IkiWiki::FailReason->new('creation_day did not match');
  1560. }
  1561. } #}}}
  1562. sub match_creation_month ($$;@) { #{{{
  1563. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1564. return IkiWiki::SuccessReason->new('creation_month matched');
  1565. }
  1566. else {
  1567. return IkiWiki::FailReason->new('creation_month did not match');
  1568. }
  1569. } #}}}
  1570. sub match_creation_year ($$;@) { #{{{
  1571. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1572. return IkiWiki::SuccessReason->new('creation_year matched');
  1573. }
  1574. else {
  1575. return IkiWiki::FailReason->new('creation_year did not match');
  1576. }
  1577. } #}}}
  1578. 1