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