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