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