summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: c15ec38220b8680b87e9dfbba0d88deb829d0280 (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 %renderedfiles %oldrenderedfiles %pagesources
  13. %destsources %depends %hooks %forcerebuild $gettext_obj
  14. %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 %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}})) {
  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 $ret=Storable::fd_retrieve($in);
  1170. if (! defined $ret) {
  1171. return 0;
  1172. }
  1173. my %index=%$ret;
  1174. foreach my $src (keys %index) {
  1175. my %d=%{$index{$src}};
  1176. my $page=pagename($src);
  1177. $pagectime{$page}=$d{ctime};
  1178. if (! $config{rebuild}) {
  1179. $pagesources{$page}=$src;
  1180. $pagemtime{$page}=$d{mtime};
  1181. $renderedfiles{$page}=$d{dest};
  1182. if (exists $d{links} && ref $d{links}) {
  1183. $links{$page}=$d{links};
  1184. $oldlinks{$page}=[@{$d{links}}];
  1185. }
  1186. if (exists $d{depends}) {
  1187. $depends{$page}=$d{depends};
  1188. }
  1189. if (exists $d{state}) {
  1190. $pagestate{$page}=$d{state};
  1191. }
  1192. }
  1193. $oldrenderedfiles{$page}=[@{$d{dest}}];
  1194. }
  1195. foreach my $page (keys %pagesources) {
  1196. $pagecase{lc $page}=$page;
  1197. }
  1198. foreach my $page (keys %renderedfiles) {
  1199. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1200. }
  1201. return close($in);
  1202. } #}}}
  1203. sub saveindex () { #{{{
  1204. run_hooks(savestate => sub { shift->() });
  1205. my %hookids;
  1206. foreach my $type (keys %hooks) {
  1207. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1208. }
  1209. my @hookids=keys %hookids;
  1210. if (! -d $config{wikistatedir}) {
  1211. mkdir($config{wikistatedir});
  1212. }
  1213. my $newfile="$config{wikistatedir}/indexdb.new";
  1214. my $cleanup = sub { unlink($newfile) };
  1215. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1216. my %index;
  1217. foreach my $page (keys %pagemtime) {
  1218. next unless $pagemtime{$page};
  1219. my $src=$pagesources{$page};
  1220. $index{$src}={
  1221. ctime => $pagectime{$page},
  1222. mtime => $pagemtime{$page},
  1223. dest => $renderedfiles{$page},
  1224. links => $links{$page},
  1225. };
  1226. if (exists $depends{$page}) {
  1227. $index{$src}{depends} = $depends{$page};
  1228. }
  1229. if (exists $pagestate{$page}) {
  1230. foreach my $id (@hookids) {
  1231. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1232. $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1233. }
  1234. }
  1235. }
  1236. }
  1237. my $ret=Storable::nstore_fd(\%index, $out);
  1238. return if ! defined $ret || ! $ret;
  1239. close $out || error("failed saving to $newfile: $!", $cleanup);
  1240. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1241. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1242. return 1;
  1243. } #}}}
  1244. sub template_file ($) { #{{{
  1245. my $template=shift;
  1246. foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
  1247. return "$dir/$template" if -e "$dir/$template";
  1248. }
  1249. return;
  1250. } #}}}
  1251. sub template_params (@) { #{{{
  1252. my $filename=template_file(shift);
  1253. if (! defined $filename) {
  1254. return if wantarray;
  1255. return "";
  1256. }
  1257. my @ret=(
  1258. filter => sub {
  1259. my $text_ref = shift;
  1260. ${$text_ref} = decode_utf8(${$text_ref});
  1261. },
  1262. filename => $filename,
  1263. loop_context_vars => 1,
  1264. die_on_bad_params => 0,
  1265. @_
  1266. );
  1267. return wantarray ? @ret : {@ret};
  1268. } #}}}
  1269. sub template ($;@) { #{{{
  1270. require HTML::Template;
  1271. return HTML::Template->new(template_params(@_));
  1272. } #}}}
  1273. sub misctemplate ($$;@) { #{{{
  1274. my $title=shift;
  1275. my $pagebody=shift;
  1276. my $template=template("misc.tmpl");
  1277. $template->param(
  1278. title => $title,
  1279. indexlink => indexlink(),
  1280. wikiname => $config{wikiname},
  1281. pagebody => $pagebody,
  1282. baseurl => baseurl(),
  1283. @_,
  1284. );
  1285. run_hooks(pagetemplate => sub {
  1286. shift->(page => "", destpage => "", template => $template);
  1287. });
  1288. return $template->output;
  1289. }#}}}
  1290. sub hook (@) { # {{{
  1291. my %param=@_;
  1292. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1293. error 'hook requires type, call, and id parameters';
  1294. }
  1295. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1296. $hooks{$param{type}}{$param{id}}=\%param;
  1297. return 1;
  1298. } # }}}
  1299. sub run_hooks ($$) { # {{{
  1300. # Calls the given sub for each hook of the given type,
  1301. # passing it the hook function to call.
  1302. my $type=shift;
  1303. my $sub=shift;
  1304. if (exists $hooks{$type}) {
  1305. my @deferred;
  1306. foreach my $id (keys %{$hooks{$type}}) {
  1307. if ($hooks{$type}{$id}{last}) {
  1308. push @deferred, $id;
  1309. next;
  1310. }
  1311. $sub->($hooks{$type}{$id}{call});
  1312. }
  1313. foreach my $id (@deferred) {
  1314. $sub->($hooks{$type}{$id}{call});
  1315. }
  1316. }
  1317. return 1;
  1318. } #}}}
  1319. sub rcs_update () { #{{{
  1320. $hooks{rcs}{rcs_update}{call}->(@_);
  1321. } #}}}
  1322. sub rcs_prepedit ($) { #{{{
  1323. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1324. } #}}}
  1325. sub rcs_commit ($$$;$$) { #{{{
  1326. $hooks{rcs}{rcs_commit}{call}->(@_);
  1327. } #}}}
  1328. sub rcs_commit_staged ($$$) { #{{{
  1329. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1330. } #}}}
  1331. sub rcs_add ($) { #{{{
  1332. $hooks{rcs}{rcs_add}{call}->(@_);
  1333. } #}}}
  1334. sub rcs_remove ($) { #{{{
  1335. $hooks{rcs}{rcs_remove}{call}->(@_);
  1336. } #}}}
  1337. sub rcs_rename ($$) { #{{{
  1338. $hooks{rcs}{rcs_rename}{call}->(@_);
  1339. } #}}}
  1340. sub rcs_recentchanges ($) { #{{{
  1341. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1342. } #}}}
  1343. sub rcs_diff ($) { #{{{
  1344. $hooks{rcs}{rcs_diff}{call}->(@_);
  1345. } #}}}
  1346. sub rcs_getctime ($) { #{{{
  1347. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1348. } #}}}
  1349. sub globlist_to_pagespec ($) { #{{{
  1350. my @globlist=split(' ', shift);
  1351. my (@spec, @skip);
  1352. foreach my $glob (@globlist) {
  1353. if ($glob=~/^!(.*)/) {
  1354. push @skip, $glob;
  1355. }
  1356. else {
  1357. push @spec, $glob;
  1358. }
  1359. }
  1360. my $spec=join(' or ', @spec);
  1361. if (@skip) {
  1362. my $skip=join(' and ', @skip);
  1363. if (length $spec) {
  1364. $spec="$skip and ($spec)";
  1365. }
  1366. else {
  1367. $spec=$skip;
  1368. }
  1369. }
  1370. return $spec;
  1371. } #}}}
  1372. sub is_globlist ($) { #{{{
  1373. my $s=shift;
  1374. return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
  1375. } #}}}
  1376. sub safequote ($) { #{{{
  1377. my $s=shift;
  1378. $s=~s/[{}]//g;
  1379. return "q{$s}";
  1380. } #}}}
  1381. sub add_depends ($$) { #{{{
  1382. my $page=shift;
  1383. my $pagespec=shift;
  1384. return unless pagespec_valid($pagespec);
  1385. if (! exists $depends{$page}) {
  1386. $depends{$page}=$pagespec;
  1387. }
  1388. else {
  1389. $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
  1390. }
  1391. return 1;
  1392. } # }}}
  1393. sub file_pruned ($$) { #{{{
  1394. require File::Spec;
  1395. my $file=File::Spec->canonpath(shift);
  1396. my $base=File::Spec->canonpath(shift);
  1397. $file =~ s#^\Q$base\E/+##;
  1398. my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1399. return $file =~ m/$regexp/ && $file ne $base;
  1400. } #}}}
  1401. sub gettext { #{{{
  1402. # Only use gettext in the rare cases it's needed.
  1403. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1404. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1405. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1406. if (! $gettext_obj) {
  1407. $gettext_obj=eval q{
  1408. use Locale::gettext q{textdomain};
  1409. Locale::gettext->domain('ikiwiki')
  1410. };
  1411. if ($@) {
  1412. print STDERR "$@";
  1413. $gettext_obj=undef;
  1414. return shift;
  1415. }
  1416. }
  1417. return $gettext_obj->get(shift);
  1418. }
  1419. else {
  1420. return shift;
  1421. }
  1422. } #}}}
  1423. sub yesno ($) { #{{{
  1424. my $val=shift;
  1425. return (defined $val && lc($val) eq gettext("yes"));
  1426. } #}}}
  1427. sub pagespec_merge ($$) { #{{{
  1428. my $a=shift;
  1429. my $b=shift;
  1430. return $a if $a eq $b;
  1431. # Support for old-style GlobLists.
  1432. if (is_globlist($a)) {
  1433. $a=globlist_to_pagespec($a);
  1434. }
  1435. if (is_globlist($b)) {
  1436. $b=globlist_to_pagespec($b);
  1437. }
  1438. return "($a) or ($b)";
  1439. } #}}}
  1440. sub pagespec_translate ($) { #{{{
  1441. my $spec=shift;
  1442. # Support for old-style GlobLists.
  1443. if (is_globlist($spec)) {
  1444. $spec=globlist_to_pagespec($spec);
  1445. }
  1446. # Convert spec to perl code.
  1447. my $code="";
  1448. while ($spec=~m{
  1449. \s* # ignore whitespace
  1450. ( # 1: match a single word
  1451. \! # !
  1452. |
  1453. \( # (
  1454. |
  1455. \) # )
  1456. |
  1457. \w+\([^\)]*\) # command(params)
  1458. |
  1459. [^\s()]+ # any other text
  1460. )
  1461. \s* # ignore whitespace
  1462. }igx) {
  1463. my $word=$1;
  1464. if (lc $word eq 'and') {
  1465. $code.=' &&';
  1466. }
  1467. elsif (lc $word eq 'or') {
  1468. $code.=' ||';
  1469. }
  1470. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1471. $code.=' '.$word;
  1472. }
  1473. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1474. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1475. $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
  1476. }
  1477. else {
  1478. $code.=' 0';
  1479. }
  1480. }
  1481. else {
  1482. $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
  1483. }
  1484. }
  1485. if (! length $code) {
  1486. $code=0;
  1487. }
  1488. no warnings;
  1489. return eval 'sub { my $page=shift; '.$code.' }';
  1490. } #}}}
  1491. sub pagespec_match ($$;@) { #{{{
  1492. my $page=shift;
  1493. my $spec=shift;
  1494. my @params=@_;
  1495. # Backwards compatability with old calling convention.
  1496. if (@params == 1) {
  1497. unshift @params, 'location';
  1498. }
  1499. my $sub=pagespec_translate($spec);
  1500. return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
  1501. return $sub->($page, @params);
  1502. } #}}}
  1503. sub pagespec_valid ($) { #{{{
  1504. my $spec=shift;
  1505. my $sub=pagespec_translate($spec);
  1506. return ! $@;
  1507. } #}}}
  1508. sub glob2re ($) { #{{{
  1509. my $re=quotemeta(shift);
  1510. $re=~s/\\\*/.*/g;
  1511. $re=~s/\\\?/./g;
  1512. return $re;
  1513. } #}}}
  1514. package IkiWiki::FailReason;
  1515. use overload ( #{{{
  1516. '""' => sub { ${$_[0]} },
  1517. '0+' => sub { 0 },
  1518. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1519. fallback => 1,
  1520. ); #}}}
  1521. sub new { #{{{
  1522. my $class = shift;
  1523. my $value = shift;
  1524. return bless \$value, $class;
  1525. } #}}}
  1526. package IkiWiki::SuccessReason;
  1527. use overload ( #{{{
  1528. '""' => sub { ${$_[0]} },
  1529. '0+' => sub { 1 },
  1530. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1531. fallback => 1,
  1532. ); #}}}
  1533. sub new { #{{{
  1534. my $class = shift;
  1535. my $value = shift;
  1536. return bless \$value, $class;
  1537. }; #}}}
  1538. package IkiWiki::PageSpec;
  1539. sub match_glob ($$;@) { #{{{
  1540. my $page=shift;
  1541. my $glob=shift;
  1542. my %params=@_;
  1543. my $from=exists $params{location} ? $params{location} : '';
  1544. # relative matching
  1545. if ($glob =~ m!^\./!) {
  1546. $from=~s#/?[^/]+$##;
  1547. $glob=~s#^\./##;
  1548. $glob="$from/$glob" if length $from;
  1549. }
  1550. my $regexp=IkiWiki::glob2re($glob);
  1551. if ($page=~/^$regexp$/i) {
  1552. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1553. return IkiWiki::SuccessReason->new("$glob matches $page");
  1554. }
  1555. else {
  1556. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1557. }
  1558. }
  1559. else {
  1560. return IkiWiki::FailReason->new("$glob does not match $page");
  1561. }
  1562. } #}}}
  1563. sub match_internal ($$;@) { #{{{
  1564. return match_glob($_[0], $_[1], @_, internal => 1)
  1565. } #}}}
  1566. sub match_link ($$;@) { #{{{
  1567. my $page=shift;
  1568. my $link=lc(shift);
  1569. my %params=@_;
  1570. my $from=exists $params{location} ? $params{location} : '';
  1571. # relative matching
  1572. if ($link =~ m!^\.! && defined $from) {
  1573. $from=~s#/?[^/]+$##;
  1574. $link=~s#^\./##;
  1575. $link="$from/$link" if length $from;
  1576. }
  1577. my $links = $IkiWiki::links{$page};
  1578. return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
  1579. my $bestlink = IkiWiki::bestlink($from, $link);
  1580. foreach my $p (@{$links}) {
  1581. if (length $bestlink) {
  1582. return IkiWiki::SuccessReason->new("$page links to $link")
  1583. if $bestlink eq IkiWiki::bestlink($page, $p);
  1584. }
  1585. else {
  1586. return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
  1587. if match_glob($p, $link, %params);
  1588. }
  1589. }
  1590. return IkiWiki::FailReason->new("$page does not link to $link");
  1591. } #}}}
  1592. sub match_backlink ($$;@) { #{{{
  1593. return match_link($_[1], $_[0], @_);
  1594. } #}}}
  1595. sub match_created_before ($$;@) { #{{{
  1596. my $page=shift;
  1597. my $testpage=shift;
  1598. if (exists $IkiWiki::pagectime{$testpage}) {
  1599. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  1600. return IkiWiki::SuccessReason->new("$page created before $testpage");
  1601. }
  1602. else {
  1603. return IkiWiki::FailReason->new("$page not created before $testpage");
  1604. }
  1605. }
  1606. else {
  1607. return IkiWiki::FailReason->new("$testpage has no ctime");
  1608. }
  1609. } #}}}
  1610. sub match_created_after ($$;@) { #{{{
  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 after $testpage");
  1616. }
  1617. else {
  1618. return IkiWiki::FailReason->new("$page not created after $testpage");
  1619. }
  1620. }
  1621. else {
  1622. return IkiWiki::FailReason->new("$testpage has no ctime");
  1623. }
  1624. } #}}}
  1625. sub match_creation_day ($$;@) { #{{{
  1626. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  1627. return IkiWiki::SuccessReason->new('creation_day matched');
  1628. }
  1629. else {
  1630. return IkiWiki::FailReason->new('creation_day did not match');
  1631. }
  1632. } #}}}
  1633. sub match_creation_month ($$;@) { #{{{
  1634. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  1635. return IkiWiki::SuccessReason->new('creation_month matched');
  1636. }
  1637. else {
  1638. return IkiWiki::FailReason->new('creation_month did not match');
  1639. }
  1640. } #}}}
  1641. sub match_creation_year ($$;@) { #{{{
  1642. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  1643. return IkiWiki::SuccessReason->new('creation_year matched');
  1644. }
  1645. else {
  1646. return IkiWiki::FailReason->new('creation_year did not match');
  1647. }
  1648. } #}}}
  1649. 1