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