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