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