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