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