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