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