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