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