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