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