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