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