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