summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: d93ff7374069684a97e35c5626ec853e02d4ce47 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use URI::Escape q{uri_escape_utf8};
  8. use POSIX;
  9. use Storable;
  10. use open qw{:utf8 :std};
  11. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  12. %pagestate %wikistate %renderedfiles %oldrenderedfiles
  13. %pagesources %destsources %depends %hooks %forcerebuild
  14. $gettext_obj %loaded_plugins};
  15. use Exporter q{import};
  16. our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
  17. bestlink htmllink readfile writefile pagetype srcfile pagename
  18. displaytime will_render gettext urlto targetpage
  19. add_underlay pagetitle titlepage linkpage newpagefile
  20. inject
  21. %config %links %pagestate %wikistate %renderedfiles
  22. %pagesources %destsources);
  23. our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
  24. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  25. my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  26. # Optimisation.
  27. use Memoize;
  28. memoize("abs2rel");
  29. memoize("pagespec_translate");
  30. memoize("file_pruned");
  31. sub getsetup () {
  32. wikiname => {
  33. type => "string",
  34. default => "wiki",
  35. description => "name of the wiki",
  36. safe => 1,
  37. rebuild => 1,
  38. },
  39. adminemail => {
  40. type => "string",
  41. default => undef,
  42. example => 'me@example.com',
  43. description => "contact email for wiki",
  44. safe => 1,
  45. rebuild => 0,
  46. },
  47. adminuser => {
  48. type => "string",
  49. default => [],
  50. description => "users who are wiki admins",
  51. safe => 1,
  52. rebuild => 0,
  53. },
  54. banned_users => {
  55. type => "string",
  56. default => [],
  57. description => "users who are banned from the wiki",
  58. safe => 1,
  59. rebuild => 0,
  60. },
  61. srcdir => {
  62. type => "string",
  63. default => undef,
  64. example => "$ENV{HOME}/wiki",
  65. description => "where the source of the wiki is located",
  66. safe => 0, # path
  67. rebuild => 1,
  68. },
  69. destdir => {
  70. type => "string",
  71. default => undef,
  72. example => "/var/www/wiki",
  73. description => "where to build the wiki",
  74. safe => 0, # path
  75. rebuild => 1,
  76. },
  77. url => {
  78. type => "string",
  79. default => '',
  80. example => "http://example.com/wiki",
  81. description => "base url to the wiki",
  82. safe => 1,
  83. rebuild => 1,
  84. },
  85. cgiurl => {
  86. type => "string",
  87. default => '',
  88. example => "http://example.com/wiki/ikiwiki.cgi",
  89. description => "url to the ikiwiki.cgi",
  90. safe => 1,
  91. rebuild => 1,
  92. },
  93. cgi_wrapper => {
  94. type => "string",
  95. default => '',
  96. example => "/var/www/wiki/ikiwiki.cgi",
  97. description => "cgi wrapper to generate",
  98. safe => 0, # file
  99. rebuild => 0,
  100. },
  101. cgi_wrappermode => {
  102. type => "string",
  103. default => '06755',
  104. description => "mode for cgi_wrapper (can safely be made suid)",
  105. safe => 0,
  106. rebuild => 0,
  107. },
  108. rcs => {
  109. type => "string",
  110. default => '',
  111. description => "rcs backend to use",
  112. safe => 0, # don't allow overriding
  113. rebuild => 0,
  114. },
  115. default_plugins => {
  116. type => "internal",
  117. default => [qw{mdwn link inline meta htmlscrubber passwordauth
  118. openid signinedit lockedit conditional
  119. recentchanges parentlinks editpage}],
  120. description => "plugins to enable by default",
  121. safe => 0,
  122. rebuild => 1,
  123. },
  124. add_plugins => {
  125. type => "string",
  126. default => [],
  127. description => "plugins to add to the default configuration",
  128. safe => 1,
  129. rebuild => 1,
  130. },
  131. disable_plugins => {
  132. type => "string",
  133. default => [],
  134. description => "plugins to disable",
  135. safe => 1,
  136. rebuild => 1,
  137. },
  138. templatedir => {
  139. type => "string",
  140. default => "$installdir/share/ikiwiki/templates",
  141. description => "location of template files",
  142. advanced => 1,
  143. safe => 0, # path
  144. rebuild => 1,
  145. },
  146. underlaydir => {
  147. type => "string",
  148. default => "$installdir/share/ikiwiki/basewiki",
  149. description => "base wiki source location",
  150. advanced => 1,
  151. safe => 0, # path
  152. rebuild => 0,
  153. },
  154. wrappers => {
  155. type => "internal",
  156. default => [],
  157. description => "wrappers to generate",
  158. safe => 0,
  159. rebuild => 0,
  160. },
  161. underlaydirs => {
  162. type => "internal",
  163. default => [],
  164. description => "additional underlays to use",
  165. safe => 0,
  166. rebuild => 0,
  167. },
  168. verbose => {
  169. type => "boolean",
  170. example => 1,
  171. description => "display verbose messages when building?",
  172. safe => 1,
  173. rebuild => 0,
  174. },
  175. syslog => {
  176. type => "boolean",
  177. example => 1,
  178. description => "log to syslog?",
  179. safe => 1,
  180. rebuild => 0,
  181. },
  182. usedirs => {
  183. type => "boolean",
  184. default => 1,
  185. description => "create output files named page/index.html?",
  186. safe => 0, # changing requires manual transition
  187. rebuild => 1,
  188. },
  189. prefix_directives => {
  190. type => "boolean",
  191. default => 0,
  192. description => "use '!'-prefixed preprocessor directives?",
  193. safe => 0, # changing requires manual transition
  194. rebuild => 1,
  195. },
  196. indexpages => {
  197. type => "boolean",
  198. default => 0,
  199. description => "use page/index.mdwn source files",
  200. safe => 1,
  201. rebuild => 1,
  202. },
  203. discussion => {
  204. type => "boolean",
  205. default => 1,
  206. description => "enable Discussion pages?",
  207. safe => 1,
  208. rebuild => 1,
  209. },
  210. sslcookie => {
  211. type => "boolean",
  212. default => 0,
  213. description => "only send cookies over SSL connections?",
  214. advanced => 1,
  215. safe => 1,
  216. rebuild => 0,
  217. },
  218. default_pageext => {
  219. type => "string",
  220. default => "mdwn",
  221. description => "extension to use for new pages",
  222. safe => 0, # not sanitized
  223. rebuild => 0,
  224. },
  225. htmlext => {
  226. type => "string",
  227. default => "html",
  228. description => "extension to use for html files",
  229. safe => 0, # not sanitized
  230. rebuild => 1,
  231. },
  232. timeformat => {
  233. type => "string",
  234. default => '%c',
  235. description => "strftime format string to display date",
  236. advanced => 1,
  237. safe => 1,
  238. rebuild => 1,
  239. },
  240. locale => {
  241. type => "string",
  242. default => undef,
  243. example => "en_US.UTF-8",
  244. description => "UTF-8 locale to use",
  245. advanced => 1,
  246. safe => 0,
  247. rebuild => 1,
  248. },
  249. userdir => {
  250. type => "string",
  251. default => "",
  252. example => "users",
  253. description => "put user pages below specified page",
  254. safe => 1,
  255. rebuild => 1,
  256. },
  257. numbacklinks => {
  258. type => "integer",
  259. default => 10,
  260. description => "how many backlinks to show before hiding excess (0 to show all)",
  261. safe => 1,
  262. rebuild => 1,
  263. },
  264. hardlink => {
  265. type => "boolean",
  266. default => 0,
  267. description => "attempt to hardlink source files? (optimisation for large files)",
  268. advanced => 1,
  269. safe => 0, # paranoia
  270. rebuild => 0,
  271. },
  272. umask => {
  273. type => "integer",
  274. 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. if ($config{usedirs}) {
  857. $url =~ s!/index.$config{htmlext}$!/!;
  858. }
  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. 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 globlist_to_pagespec ($) {
  1413. my @globlist=split(' ', shift);
  1414. my (@spec, @skip);
  1415. foreach my $glob (@globlist) {
  1416. if ($glob=~/^!(.*)/) {
  1417. push @skip, $glob;
  1418. }
  1419. else {
  1420. push @spec, $glob;
  1421. }
  1422. }
  1423. my $spec=join(' or ', @spec);
  1424. if (@skip) {
  1425. my $skip=join(' and ', @skip);
  1426. if (length $spec) {
  1427. $spec="$skip and ($spec)";
  1428. }
  1429. else {
  1430. $spec=$skip;
  1431. }
  1432. }
  1433. return $spec;
  1434. }
  1435. sub is_globlist ($) {
  1436. my $s=shift;
  1437. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  1438. }
  1439. sub safequote ($) {
  1440. my $s=shift;
  1441. $s=~s/[{}]//g;
  1442. return "q{$s}";
  1443. }
  1444. sub add_depends ($$) {
  1445. my $page=shift;
  1446. my $pagespec=shift;
  1447. return unless pagespec_valid($pagespec);
  1448. if (! exists $depends{$page}) {
  1449. $depends{$page}=$pagespec;
  1450. }
  1451. else {
  1452. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1453. }
  1454. return 1;
  1455. }
  1456. sub file_pruned ($$) {
  1457. require File::Spec;
  1458. my $file=File::Spec->canonpath(shift);
  1459. my $base=File::Spec->canonpath(shift);
  1460. $file =~ s#^\Q$base\E/+##;
  1461. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1462. return $file =~ m/$regexp/ && $file ne $base;
  1463. }
  1464. sub gettext {
  1465. # Only use gettext in the rare cases it's needed.
  1466. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1467. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1468. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1469. if (! $gettext_obj) {
  1470. $gettext_obj=eval q{
  1471. use Locale::gettext q{textdomain};
  1472. Locale::gettext->domain('ikiwiki')
  1473. };
  1474. if ($@) {
  1475. print STDERR "$@";
  1476. $gettext_obj=undef;
  1477. return shift;
  1478. }
  1479. }
  1480. return $gettext_obj->get(shift);
  1481. }
  1482. else {
  1483. return shift;
  1484. }
  1485. }
  1486. sub yesno ($) {
  1487. my $val=shift;
  1488. return (defined $val && lc($val) eq gettext("yes"));
  1489. }
  1490. sub inject {
  1491. # Injects a new function into the symbol table to replace an
  1492. # exported function.
  1493. my %params=@_;
  1494. # This is deep ugly perl foo, beware.
  1495. no strict;
  1496. no warnings;
  1497. if (! defined $params{parent}) {
  1498. $params{parent}='::';
  1499. $params{old}=\&{$params{name}};
  1500. $params{name}=~s/.*:://;
  1501. }
  1502. my $parent=$params{parent};
  1503. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1504. $ns = $params{parent} . $ns;
  1505. inject(%params, parent => $ns) unless $ns eq '::main::';
  1506. *{$ns . $params{name}} = $params{call}
  1507. if exists ${$ns}{$params{name}} &&
  1508. \&{${$ns}{$params{name}}} == $params{old};
  1509. }
  1510. use strict;
  1511. use warnings;
  1512. }
  1513. sub pagespec_merge ($$) {
  1514. my $a=shift;
  1515. my $b=shift;
  1516. return $a if $a eq $b;
  1517. # Support for old-style GlobLists.
  1518. if (is_globlist($a)) {
  1519. $a=globlist_to_pagespec($a);
  1520. }
  1521. if (is_globlist($b)) {
  1522. $b=globlist_to_pagespec($b);
  1523. }
  1524. return "($a) or ($b)";
  1525. }
  1526. sub pagespec_translate ($) {
  1527. my $spec=shift;
  1528. # Support for old-style GlobLists.
  1529. if (is_globlist($spec)) {
  1530. $spec=globlist_to_pagespec($spec);
  1531. }
  1532. # Convert spec to perl code.
  1533. my $code="";
  1534. while ($spec=~m{
  1535. \s* # ignore whitespace
  1536. ( # 1: match a single word
  1537. \! # !
  1538. |
  1539. \( # (
  1540. |
  1541. \) # )
  1542. |
  1543. \w+\([^\)]*\) # command(params)
  1544. |
  1545. [^\s()]+ # any other text
  1546. )
  1547. \s* # ignore whitespace
  1548. }igx) {
  1549. my $word=$1;
  1550. if (lc $word eq 'and') {
  1551. $code.=' &&';
  1552. }
  1553. elsif (lc $word eq 'or') {
  1554. $code.=' ||';
  1555. }
  1556. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1557. $code.=' '.$word;
  1558. }
  1559. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1560. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1561. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1562. }
  1563. else {
  1564. $code.=' 0';
  1565. }
  1566. }
  1567. else {
  1568. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1569. }
  1570. }
  1571. if (! length $code) {
  1572. $code=0;
  1573. }
  1574. no warnings;
  1575. return eval 'sub { my $page=shift; '.$code.' }';
  1576. }
  1577. sub pagespec_match ($$;@) {
  1578. my $page=shift;
  1579. my $spec=shift;
  1580. my @params=@_;
  1581. # Backwards compatability with old calling convention.
  1582. if (@params == 1) {
  1583. unshift @params, 'location';
  1584. }
  1585. my $sub=pagespec_translate($spec);
  1586. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1587. return $sub->($page, @params);
  1588. }
  1589. sub pagespec_valid ($) {
  1590. my $spec=shift;
  1591. my $sub=pagespec_translate($spec);
  1592. return ! $@;
  1593. }
  1594. sub glob2re ($) {
  1595. my $re=quotemeta(shift);
  1596. $re=~s/\\\*/.*/g;
  1597. $re=~s/\\\?/./g;
  1598. return $re;
  1599. }
  1600. package IkiWiki::FailReason;
  1601. use overload (
  1602. '""' => sub { ${$_[0]} },
  1603. '0+' => sub { 0 },
  1604. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1605. fallback => 1,
  1606. );
  1607. sub new {
  1608. my $class = shift;
  1609. my $value = shift;
  1610. return bless \$value, $class;
  1611. }
  1612. package IkiWiki::SuccessReason;
  1613. use overload (
  1614. '""' => sub { ${$_[0]} },
  1615. '0+' => sub { 1 },
  1616. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1617. fallback => 1,
  1618. );
  1619. sub new {
  1620. my $class = shift;
  1621. my $value = shift;
  1622. return bless \$value, $class;
  1623. };
  1624. package IkiWiki::PageSpec;
  1625. sub match_glob ($$;@) {
  1626. my $page=shift;
  1627. my $glob=shift;
  1628. my %params=@_;
  1629. my $from=exists $params{location} ? $params{location} : '';
  1630. # relative matching
  1631. if ($glob =~ m!^\./!) {
  1632. $from=~s#/?[^/]+$##;
  1633. $glob=~s#^\./##;
  1634. $glob="$from/$glob" if length $from;
  1635. }
  1636. my $regexp=IkiWiki::glob2re($glob);
  1637. if ($page=~/^$regexp$/i) {
  1638. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1639. return IkiWiki::SuccessReason->new("$glob matches $page");
  1640. }
  1641. else {
  1642. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1643. }
  1644. }
  1645. else {
  1646. return IkiWiki::FailReason->new("$glob does not match $page");
  1647. }
  1648. }
  1649. sub match_internal ($$;@) {
  1650. return match_glob($_[0], $_[1], @_, internal => 1)
  1651. }
  1652. sub match_link ($$;@) {
  1653. my $page=shift;
  1654. my $link=lc(shift);
  1655. my %params=@_;
  1656. my $from=exists $params{location} ? $params{location} : '';
  1657. # relative matching
  1658. if ($link =~ m!^\.! && defined $from) {
  1659. $from=~s#/?[^/]+$##;
  1660. $link=~s#^\./##;
  1661. $link="$from/$link" if length $from;
  1662. }
  1663. my $links = $IkiWiki::links{$page};
  1664. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1665. my $bestlink = IkiWiki::bestlink($from, $link);
  1666. foreach my $p (@{$links}) {
  1667. if (length $bestlink) {
  1668. return IkiWiki::SuccessReason->new("$page links to $link")
  1669. if $bestlink eq IkiWiki::bestlink($page, $p);
  1670. }
  1671. else {
  1672. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1673. if match_glob($p, $link, %params);
  1674. $p=~s/^\///;
  1675. $link=~s/^\///;
  1676. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1677. if match_glob($p, $link, %params);
  1678. }
  1679. }
  1680. return IkiWiki::FailReason->new("$page does not link to $link");
  1681. }
  1682. sub match_backlink ($$;@) {
  1683. return match_link($_[1], $_[0], @_);
  1684. }
  1685. sub match_created_before ($$;@) {
  1686. my $page=shift;
  1687. my $testpage=shift;
  1688. if (exists $IkiWiki::pagectime{$testpage}) {
  1689. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1690. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1691. }
  1692. else {
  1693. return IkiWiki::FailReason->new("$page not created before $testpage");
  1694. }
  1695. }
  1696. else {
  1697. return IkiWiki::FailReason->new("$testpage has no ctime");
  1698. }
  1699. }
  1700. sub match_created_after ($$;@) {
  1701. my $page=shift;
  1702. my $testpage=shift;
  1703. if (exists $IkiWiki::pagectime{$testpage}) {
  1704. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  1705. return IkiWiki::SuccessReason->new("$page created after $testpage");
  1706. }
  1707. else {
  1708. return IkiWiki::FailReason->new("$page not created after $testpage");
  1709. }
  1710. }
  1711. else {
  1712. return IkiWiki::FailReason->new("$testpage has no ctime");
  1713. }
  1714. }
  1715. sub match_creation_day ($$;@) {
  1716. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1717. return IkiWiki::SuccessReason->new('creation_day matched');
  1718. }
  1719. else {
  1720. return IkiWiki::FailReason->new('creation_day did not match');
  1721. }
  1722. }
  1723. sub match_creation_month ($$;@) {
  1724. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1725. return IkiWiki::SuccessReason->new('creation_month matched');
  1726. }
  1727. else {
  1728. return IkiWiki::FailReason->new('creation_month did not match');
  1729. }
  1730. }
  1731. sub match_creation_year ($$;@) {
  1732. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1733. return IkiWiki::SuccessReason->new('creation_year matched');
  1734. }
  1735. else {
  1736. return IkiWiki::FailReason->new('creation_year did not match');
  1737. }
  1738. }
  1739. sub match_user ($$;@) {
  1740. shift;
  1741. my $user=shift;
  1742. my %params=@_;
  1743. if (! exists $params{user}) {
  1744. return IkiWiki::FailReason->new("no user specified");
  1745. }
  1746. if (defined $params{user} && lc $params{user} eq lc $user) {
  1747. return IkiWiki::SuccessReason->new("user is $user");
  1748. }
  1749. elsif (! defined $params{user}) {
  1750. return IkiWiki::FailReason->new("not logged in");
  1751. }
  1752. else {
  1753. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  1754. }
  1755. }
  1756. sub match_admin ($$;@) {
  1757. shift;
  1758. shift;
  1759. my %params=@_;
  1760. if (! exists $params{user}) {
  1761. return IkiWiki::FailReason->new("no user specified");
  1762. }
  1763. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  1764. return IkiWiki::SuccessReason->new("user is an admin");
  1765. }
  1766. elsif (! defined $params{user}) {
  1767. return IkiWiki::FailReason->new("not logged in");
  1768. }
  1769. else {
  1770. return IkiWiki::FailReason->new("user is not an admin");
  1771. }
  1772. }
  1773. sub match_ip ($$;@) {
  1774. shift;
  1775. my $ip=shift;
  1776. my %params=@_;
  1777. if (! exists $params{ip}) {
  1778. return IkiWiki::FailReason->new("no IP specified");
  1779. }
  1780. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  1781. return IkiWiki::SuccessReason->new("IP is $ip");
  1782. }
  1783. else {
  1784. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  1785. }
  1786. }
  1787. 1