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