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