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