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