summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: dc9b66344ae8529b24aec6b993e09f951f267b2b (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. my $wait=@_ ? shift : 1;
  1144. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1145. # run issues. The lock will be dropped on program exit.
  1146. if (! -d $config{wikistatedir}) {
  1147. mkdir($config{wikistatedir});
  1148. }
  1149. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1150. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1151. if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
  1152. if ($wait) {
  1153. debug("wiki seems to be locked, waiting for lock");
  1154. my $wait=600; # arbitrary, but don't hang forever to
  1155. # prevent process pileup
  1156. for (1..$wait) {
  1157. return if flock($wikilock, 2 | 4);
  1158. sleep 1;
  1159. }
  1160. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  1161. }
  1162. else {
  1163. return 0;
  1164. }
  1165. }
  1166. return 1;
  1167. } #}}}
  1168. sub unlockwiki () { #{{{
  1169. return close($wikilock) if $wikilock;
  1170. return;
  1171. } #}}}
  1172. my $commitlock;
  1173. sub commit_hook_enabled () { #{{{
  1174. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1175. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1176. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1177. close($commitlock) || error("failed closing commitlock: $!");
  1178. return 0;
  1179. }
  1180. close($commitlock) || error("failed closing commitlock: $!");
  1181. return 1;
  1182. } #}}}
  1183. sub disable_commit_hook () { #{{{
  1184. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1185. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1186. if (! flock($commitlock, 2)) { # LOCK_EX
  1187. error("failed to get commit lock");
  1188. }
  1189. return 1;
  1190. } #}}}
  1191. sub enable_commit_hook () { #{{{
  1192. return close($commitlock) if $commitlock;
  1193. return;
  1194. } #}}}
  1195. sub loadindex () { #{{{
  1196. %oldrenderedfiles=%pagectime=();
  1197. if (! $config{rebuild}) {
  1198. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1199. %destsources=%renderedfiles=%pagecase=%pagestate=();
  1200. }
  1201. my $in;
  1202. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1203. if (-e "$config{wikistatedir}/index") {
  1204. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1205. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1206. }
  1207. else {
  1208. return;
  1209. }
  1210. }
  1211. my $index=Storable::fd_retrieve($in);
  1212. if (! defined $index) {
  1213. return 0;
  1214. }
  1215. my $pages;
  1216. if (exists $index->{version} && ! ref $index->{version}) {
  1217. $pages=$index->{page};
  1218. %wikistate=%{$index->{state}};
  1219. }
  1220. else {
  1221. $pages=$index;
  1222. %wikistate=();
  1223. }
  1224. foreach my $src (keys %$pages) {
  1225. my $d=$pages->{$src};
  1226. my $page=pagename($src);
  1227. $pagectime{$page}=$d->{ctime};
  1228. if (! $config{rebuild}) {
  1229. $pagesources{$page}=$src;
  1230. $pagemtime{$page}=$d->{mtime};
  1231. $renderedfiles{$page}=$d->{dest};
  1232. if (exists $d->{links} && ref $d->{links}) {
  1233. $links{$page}=$d->{links};
  1234. $oldlinks{$page}=[@{$d->{links}}];
  1235. }
  1236. if (exists $d->{depends}) {
  1237. $depends{$page}=$d->{depends};
  1238. }
  1239. if (exists $d->{state}) {
  1240. $pagestate{$page}=$d->{state};
  1241. }
  1242. }
  1243. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1244. }
  1245. foreach my $page (keys %pagesources) {
  1246. $pagecase{lc $page}=$page;
  1247. }
  1248. foreach my $page (keys %renderedfiles) {
  1249. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1250. }
  1251. return close($in);
  1252. } #}}}
  1253. sub saveindex () { #{{{
  1254. run_hooks(savestate => sub { shift->() });
  1255. my %hookids;
  1256. foreach my $type (keys %hooks) {
  1257. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1258. }
  1259. my @hookids=keys %hookids;
  1260. if (! -d $config{wikistatedir}) {
  1261. mkdir($config{wikistatedir});
  1262. }
  1263. my $newfile="$config{wikistatedir}/indexdb.new";
  1264. my $cleanup = sub { unlink($newfile) };
  1265. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1266. my %index;
  1267. foreach my $page (keys %pagemtime) {
  1268. next unless $pagemtime{$page};
  1269. my $src=$pagesources{$page};
  1270. $index{page}{$src}={
  1271. ctime => $pagectime{$page},
  1272. mtime => $pagemtime{$page},
  1273. dest => $renderedfiles{$page},
  1274. links => $links{$page},
  1275. };
  1276. if (exists $depends{$page}) {
  1277. $index{page}{$src}{depends} = $depends{$page};
  1278. }
  1279. if (exists $pagestate{$page}) {
  1280. foreach my $id (@hookids) {
  1281. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1282. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1283. }
  1284. }
  1285. }
  1286. }
  1287. $index{state}={};
  1288. foreach my $id (@hookids) {
  1289. foreach my $key (keys %{$wikistate{$id}}) {
  1290. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1291. }
  1292. }
  1293. $index{version}="3";
  1294. my $ret=Storable::nstore_fd(\%index, $out);
  1295. return if ! defined $ret || ! $ret;
  1296. close $out || error("failed saving to $newfile: $!", $cleanup);
  1297. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1298. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1299. return 1;
  1300. } #}}}
  1301. sub template_file ($) { #{{{
  1302. my $template=shift;
  1303. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1304. return "$dir/$template" if -e "$dir/$template";
  1305. }
  1306. return;
  1307. } #}}}
  1308. sub template_params (@) { #{{{
  1309. my $filename=template_file(shift);
  1310. if (! defined $filename) {
  1311. return if wantarray;
  1312. return "";
  1313. }
  1314. my @ret=(
  1315. filter => sub {
  1316. my $text_ref = shift;
  1317. ${$text_ref} = decode_utf8(${$text_ref});
  1318. },
  1319. filename => $filename,
  1320. loop_context_vars => 1,
  1321. die_on_bad_params => 0,
  1322. @_
  1323. );
  1324. return wantarray ? @ret : {@ret};
  1325. } #}}}
  1326. sub template ($;@) { #{{{
  1327. require HTML::Template;
  1328. return HTML::Template->new(template_params(@_));
  1329. } #}}}
  1330. sub misctemplate ($$;@) { #{{{
  1331. my $title=shift;
  1332. my $pagebody=shift;
  1333. my $template=template("misc.tmpl");
  1334. $template->param(
  1335. title => $title,
  1336. indexlink => indexlink(),
  1337. wikiname => $config{wikiname},
  1338. pagebody => $pagebody,
  1339. baseurl => baseurl(),
  1340. @_,
  1341. );
  1342. run_hooks(pagetemplate => sub {
  1343. shift->(page => "", destpage => "", template => $template);
  1344. });
  1345. return $template->output;
  1346. }#}}}
  1347. sub hook (@) { # {{{
  1348. my %param=@_;
  1349. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1350. error 'hook requires type, call, and id parameters';
  1351. }
  1352. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1353. $hooks{$param{type}}{$param{id}}=\%param;
  1354. return 1;
  1355. } # }}}
  1356. sub run_hooks ($$) { # {{{
  1357. # Calls the given sub for each hook of the given type,
  1358. # passing it the hook function to call.
  1359. my $type=shift;
  1360. my $sub=shift;
  1361. if (exists $hooks{$type}) {
  1362. my @deferred;
  1363. foreach my $id (keys %{$hooks{$type}}) {
  1364. if ($hooks{$type}{$id}{last}) {
  1365. push @deferred, $id;
  1366. next;
  1367. }
  1368. $sub->($hooks{$type}{$id}{call});
  1369. }
  1370. foreach my $id (@deferred) {
  1371. $sub->($hooks{$type}{$id}{call});
  1372. }
  1373. }
  1374. return 1;
  1375. } #}}}
  1376. sub rcs_update () { #{{{
  1377. $hooks{rcs}{rcs_update}{call}->(@_);
  1378. } #}}}
  1379. sub rcs_prepedit ($) { #{{{
  1380. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1381. } #}}}
  1382. sub rcs_commit ($$$;$$) { #{{{
  1383. $hooks{rcs}{rcs_commit}{call}->(@_);
  1384. } #}}}
  1385. sub rcs_commit_staged ($$$) { #{{{
  1386. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1387. } #}}}
  1388. sub rcs_add ($) { #{{{
  1389. $hooks{rcs}{rcs_add}{call}->(@_);
  1390. } #}}}
  1391. sub rcs_remove ($) { #{{{
  1392. $hooks{rcs}{rcs_remove}{call}->(@_);
  1393. } #}}}
  1394. sub rcs_rename ($$) { #{{{
  1395. $hooks{rcs}{rcs_rename}{call}->(@_);
  1396. } #}}}
  1397. sub rcs_recentchanges ($) { #{{{
  1398. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1399. } #}}}
  1400. sub rcs_diff ($) { #{{{
  1401. $hooks{rcs}{rcs_diff}{call}->(@_);
  1402. } #}}}
  1403. sub rcs_getctime ($) { #{{{
  1404. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1405. } #}}}
  1406. sub rcs_receive () { #{{{
  1407. $hooks{rcs}{rcs_receive}{call}->();
  1408. } #}}}
  1409. sub globlist_to_pagespec ($) { #{{{
  1410. my @globlist=split(' ', shift);
  1411. my (@spec, @skip);
  1412. foreach my $glob (@globlist) {
  1413. if ($glob=~/^!(.*)/) {
  1414. push @skip, $glob;
  1415. }
  1416. else {
  1417. push @spec, $glob;
  1418. }
  1419. }
  1420. my $spec=join(' or ', @spec);
  1421. if (@skip) {
  1422. my $skip=join(' and ', @skip);
  1423. if (length $spec) {
  1424. $spec="$skip and ($spec)";
  1425. }
  1426. else {
  1427. $spec=$skip;
  1428. }
  1429. }
  1430. return $spec;
  1431. } #}}}
  1432. sub is_globlist ($) { #{{{
  1433. my $s=shift;
  1434. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  1435. } #}}}
  1436. sub safequote ($) { #{{{
  1437. my $s=shift;
  1438. $s=~s/[{}]//g;
  1439. return "q{$s}";
  1440. } #}}}
  1441. sub add_depends ($$) { #{{{
  1442. my $page=shift;
  1443. my $pagespec=shift;
  1444. return unless pagespec_valid($pagespec);
  1445. if (! exists $depends{$page}) {
  1446. $depends{$page}=$pagespec;
  1447. }
  1448. else {
  1449. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1450. }
  1451. return 1;
  1452. } # }}}
  1453. sub file_pruned ($$) { #{{{
  1454. require File::Spec;
  1455. my $file=File::Spec->canonpath(shift);
  1456. my $base=File::Spec->canonpath(shift);
  1457. $file =~ s#^\Q$base\E/+##;
  1458. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1459. return $file =~ m/$regexp/ && $file ne $base;
  1460. } #}}}
  1461. sub gettext { #{{{
  1462. # Only use gettext in the rare cases it's needed.
  1463. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1464. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1465. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1466. if (! $gettext_obj) {
  1467. $gettext_obj=eval q{
  1468. use Locale::gettext q{textdomain};
  1469. Locale::gettext->domain('ikiwiki')
  1470. };
  1471. if ($@) {
  1472. print STDERR "$@";
  1473. $gettext_obj=undef;
  1474. return shift;
  1475. }
  1476. }
  1477. return $gettext_obj->get(shift);
  1478. }
  1479. else {
  1480. return shift;
  1481. }
  1482. } #}}}
  1483. sub yesno ($) { #{{{
  1484. my $val=shift;
  1485. return (defined $val && lc($val) eq gettext("yes"));
  1486. } #}}}
  1487. sub inject { #{{{
  1488. # Injects a new function into the symbol table to replace an
  1489. # exported function.
  1490. my %params=@_;
  1491. # This is deep ugly perl foo, beware.
  1492. no strict;
  1493. no warnings;
  1494. if (! defined $params{parent}) {
  1495. $params{parent}='::';
  1496. $params{old}=\&{$params{name}};
  1497. $params{name}=~s/.*:://;
  1498. }
  1499. my $parent=$params{parent};
  1500. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1501. $ns = $params{parent} . $ns;
  1502. inject(%params, parent => $ns) unless $ns eq '::main::';
  1503. *{$ns . $params{name}} = $params{call}
  1504. if exists ${$ns}{$params{name}} &&
  1505. \&{${$ns}{$params{name}}} == $params{old};
  1506. }
  1507. use strict;
  1508. use warnings;
  1509. } #}}}
  1510. sub pagespec_merge ($$) { #{{{
  1511. my $a=shift;
  1512. my $b=shift;
  1513. return $a if $a eq $b;
  1514. # Support for old-style GlobLists.
  1515. if (is_globlist($a)) {
  1516. $a=globlist_to_pagespec($a);
  1517. }
  1518. if (is_globlist($b)) {
  1519. $b=globlist_to_pagespec($b);
  1520. }
  1521. return "($a) or ($b)";
  1522. } #}}}
  1523. sub pagespec_translate ($) { #{{{
  1524. my $spec=shift;
  1525. # Support for old-style GlobLists.
  1526. if (is_globlist($spec)) {
  1527. $spec=globlist_to_pagespec($spec);
  1528. }
  1529. # Convert spec to perl code.
  1530. my $code="";
  1531. while ($spec=~m{
  1532. \s* # ignore whitespace
  1533. ( # 1: match a single word
  1534. \! # !
  1535. |
  1536. \( # (
  1537. |
  1538. \) # )
  1539. |
  1540. \w+\([^\)]*\) # command(params)
  1541. |
  1542. [^\s()]+ # any other text
  1543. )
  1544. \s* # ignore whitespace
  1545. }igx) {
  1546. my $word=$1;
  1547. if (lc $word eq 'and') {
  1548. $code.=' &&';
  1549. }
  1550. elsif (lc $word eq 'or') {
  1551. $code.=' ||';
  1552. }
  1553. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1554. $code.=' '.$word;
  1555. }
  1556. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1557. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1558. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1559. }
  1560. else {
  1561. $code.=' 0';
  1562. }
  1563. }
  1564. else {
  1565. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1566. }
  1567. }
  1568. if (! length $code) {
  1569. $code=0;
  1570. }
  1571. no warnings;
  1572. return eval 'sub { my $page=shift; '.$code.' }';
  1573. } #}}}
  1574. sub pagespec_match ($$;@) { #{{{
  1575. my $page=shift;
  1576. my $spec=shift;
  1577. my @params=@_;
  1578. # Backwards compatability with old calling convention.
  1579. if (@params == 1) {
  1580. unshift @params, 'location';
  1581. }
  1582. my $sub=pagespec_translate($spec);
  1583. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1584. return $sub->($page, @params);
  1585. } #}}}
  1586. sub pagespec_valid ($) { #{{{
  1587. my $spec=shift;
  1588. my $sub=pagespec_translate($spec);
  1589. return ! $@;
  1590. } #}}}
  1591. sub glob2re ($) { #{{{
  1592. my $re=quotemeta(shift);
  1593. $re=~s/\\\*/.*/g;
  1594. $re=~s/\\\?/./g;
  1595. return $re;
  1596. } #}}}
  1597. package IkiWiki::FailReason;
  1598. use overload ( #{{{
  1599. '""' => sub { ${$_[0]} },
  1600. '0+' => sub { 0 },
  1601. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1602. fallback => 1,
  1603. ); #}}}
  1604. sub new { #{{{
  1605. my $class = shift;
  1606. my $value = shift;
  1607. return bless \$value, $class;
  1608. } #}}}
  1609. package IkiWiki::SuccessReason;
  1610. use overload ( #{{{
  1611. '""' => sub { ${$_[0]} },
  1612. '0+' => sub { 1 },
  1613. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1614. fallback => 1,
  1615. ); #}}}
  1616. sub new { #{{{
  1617. my $class = shift;
  1618. my $value = shift;
  1619. return bless \$value, $class;
  1620. }; #}}}
  1621. package IkiWiki::PageSpec;
  1622. sub match_glob ($$;@) { #{{{
  1623. my $page=shift;
  1624. my $glob=shift;
  1625. my %params=@_;
  1626. my $from=exists $params{location} ? $params{location} : '';
  1627. # relative matching
  1628. if ($glob =~ m!^\./!) {
  1629. $from=~s#/?[^/]+$##;
  1630. $glob=~s#^\./##;
  1631. $glob="$from/$glob" if length $from;
  1632. }
  1633. my $regexp=IkiWiki::glob2re($glob);
  1634. if ($page=~/^$regexp$/i) {
  1635. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1636. return IkiWiki::SuccessReason->new("$glob matches $page");
  1637. }
  1638. else {
  1639. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1640. }
  1641. }
  1642. else {
  1643. return IkiWiki::FailReason->new("$glob does not match $page");
  1644. }
  1645. } #}}}
  1646. sub match_internal ($$;@) { #{{{
  1647. return match_glob($_[0], $_[1], @_, internal => 1)
  1648. } #}}}
  1649. sub match_link ($$;@) { #{{{
  1650. my $page=shift;
  1651. my $link=lc(shift);
  1652. my %params=@_;
  1653. my $from=exists $params{location} ? $params{location} : '';
  1654. # relative matching
  1655. if ($link =~ m!^\.! && defined $from) {
  1656. $from=~s#/?[^/]+$##;
  1657. $link=~s#^\./##;
  1658. $link="$from/$link" if length $from;
  1659. }
  1660. my $links = $IkiWiki::links{$page};
  1661. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1662. my $bestlink = IkiWiki::bestlink($from, $link);
  1663. foreach my $p (@{$links}) {
  1664. if (length $bestlink) {
  1665. return IkiWiki::SuccessReason->new("$page links to $link")
  1666. if $bestlink eq IkiWiki::bestlink($page, $p);
  1667. }
  1668. else {
  1669. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1670. if match_glob($p, $link, %params);
  1671. $p=~s/^\///;
  1672. $link=~s/^\///;
  1673. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1674. if match_glob($p, $link, %params);
  1675. }
  1676. }
  1677. return IkiWiki::FailReason->new("$page does not link to $link");
  1678. } #}}}
  1679. sub match_backlink ($$;@) { #{{{
  1680. return match_link($_[1], $_[0], @_);
  1681. } #}}}
  1682. sub match_created_before ($$;@) { #{{{
  1683. my $page=shift;
  1684. my $testpage=shift;
  1685. if (exists $IkiWiki::pagectime{$testpage}) {
  1686. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1687. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1688. }
  1689. else {
  1690. return IkiWiki::FailReason->new("$page not created before $testpage");
  1691. }
  1692. }
  1693. else {
  1694. return IkiWiki::FailReason->new("$testpage has no ctime");
  1695. }
  1696. } #}}}
  1697. sub match_created_after ($$;@) { #{{{
  1698. my $page=shift;
  1699. my $testpage=shift;
  1700. if (exists $IkiWiki::pagectime{$testpage}) {
  1701. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1702. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1703. }
  1704. else {
  1705. return IkiWiki::FailReason->new("$page not created after $testpage");
  1706. }
  1707. }
  1708. else {
  1709. return IkiWiki::FailReason->new("$testpage has no ctime");
  1710. }
  1711. } #}}}
  1712. sub match_creation_day ($$;@) { #{{{
  1713. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1714. return IkiWiki::SuccessReason->new('creation_day matched');
  1715. }
  1716. else {
  1717. return IkiWiki::FailReason->new('creation_day did not match');
  1718. }
  1719. } #}}}
  1720. sub match_creation_month ($$;@) { #{{{
  1721. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1722. return IkiWiki::SuccessReason->new('creation_month matched');
  1723. }
  1724. else {
  1725. return IkiWiki::FailReason->new('creation_month did not match');
  1726. }
  1727. } #}}}
  1728. sub match_creation_year ($$;@) { #{{{
  1729. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1730. return IkiWiki::SuccessReason->new('creation_year matched');
  1731. }
  1732. else {
  1733. return IkiWiki::FailReason->new('creation_year did not match');
  1734. }
  1735. } #}}}
  1736. sub match_user ($$;@) { #{{{
  1737. shift;
  1738. my $user=shift;
  1739. my %params=@_;
  1740. if (! exists $params{user}) {
  1741. return IkiWiki::FailReason->new("no user specified");
  1742. }
  1743. if (defined $params{user} && lc $params{user} eq lc $user) {
  1744. return IkiWiki::SuccessReason->new("user is $user");
  1745. }
  1746. elsif (! defined $params{user}) {
  1747. return IkiWiki::FailReason->new("not logged in");
  1748. }
  1749. else {
  1750. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1751. }
  1752. } #}}}
  1753. sub match_admin ($$;@) { #{{{
  1754. shift;
  1755. shift;
  1756. my %params=@_;
  1757. if (! exists $params{user}) {
  1758. return IkiWiki::FailReason->new("no user specified");
  1759. }
  1760. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1761. return IkiWiki::SuccessReason->new("user is an admin");
  1762. }
  1763. elsif (! defined $params{user}) {
  1764. return IkiWiki::FailReason->new("not logged in");
  1765. }
  1766. else {
  1767. return IkiWiki::FailReason->new("user is not an admin");
  1768. }
  1769. } #}}}
  1770. sub match_ip ($$;@) { #{{{
  1771. shift;
  1772. my $ip=shift;
  1773. my %params=@_;
  1774. if (! exists $params{ip}) {
  1775. return IkiWiki::FailReason->new("no IP specified");
  1776. }
  1777. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1778. return IkiWiki::SuccessReason->new("IP is $ip");
  1779. }
  1780. else {
  1781. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1782. }
  1783. } #}}}
  1784. 1