summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 1c05a7aa55215d638400831066b1ee17496b15b9 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use URI::Escape q{uri_escape_utf8};
  7. use POSIX ();
  8. use Storable;
  9. use open qw{:utf8 :std};
  10. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  11. %pagestate %wikistate %renderedfiles %oldrenderedfiles
  12. %pagesources %delpagesources %destsources %depends %depends_simple
  13. @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
  14. %oldtypedlinks %autofiles};
  15. use Exporter q{import};
  16. our @EXPORT = qw(hook debug error htmlpage template template_depends
  17. deptype add_depends pagespec_match pagespec_match_list bestlink
  18. htmllink readfile writefile pagetype srcfile pagename
  19. displaytime will_render gettext ngettext urlto targetpage
  20. add_underlay pagetitle titlepage linkpage newpagefile
  21. inject add_link add_autofile
  22. %config %links %pagestate %wikistate %renderedfiles
  23. %pagesources %destsources %typedlinks);
  24. our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
  25. our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
  26. our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
  27. # Page dependency types.
  28. our $DEPEND_CONTENT=1;
  29. our $DEPEND_PRESENCE=2;
  30. our $DEPEND_LINKS=4;
  31. # Optimisation.
  32. use Memoize;
  33. memoize("abs2rel");
  34. memoize("sortspec_translate");
  35. memoize("pagespec_translate");
  36. memoize("template_file");
  37. sub getsetup () {
  38. wikiname => {
  39. type => "string",
  40. default => "wiki",
  41. description => "name of the wiki",
  42. safe => 1,
  43. rebuild => 1,
  44. },
  45. adminemail => {
  46. type => "string",
  47. default => undef,
  48. example => 'me@example.com',
  49. description => "contact email for wiki",
  50. safe => 1,
  51. rebuild => 0,
  52. },
  53. adminuser => {
  54. type => "string",
  55. default => [],
  56. description => "users who are wiki admins",
  57. safe => 1,
  58. rebuild => 0,
  59. },
  60. banned_users => {
  61. type => "string",
  62. default => [],
  63. description => "users who are banned from the wiki",
  64. safe => 1,
  65. rebuild => 0,
  66. },
  67. srcdir => {
  68. type => "string",
  69. default => undef,
  70. example => "$ENV{HOME}/wiki",
  71. description => "where the source of the wiki is located",
  72. safe => 0, # path
  73. rebuild => 1,
  74. },
  75. destdir => {
  76. type => "string",
  77. default => undef,
  78. example => "/var/www/wiki",
  79. description => "where to build the wiki",
  80. safe => 0, # path
  81. rebuild => 1,
  82. },
  83. url => {
  84. type => "string",
  85. default => '',
  86. example => "http://example.com/wiki",
  87. description => "base url to the wiki",
  88. safe => 1,
  89. rebuild => 1,
  90. },
  91. cgiurl => {
  92. type => "string",
  93. default => '',
  94. example => "http://example.com/wiki/ikiwiki.cgi",
  95. description => "url to the ikiwiki.cgi",
  96. safe => 1,
  97. rebuild => 1,
  98. },
  99. cgi_wrapper => {
  100. type => "string",
  101. default => '',
  102. example => "/var/www/wiki/ikiwiki.cgi",
  103. description => "filename of cgi wrapper to generate",
  104. safe => 0, # file
  105. rebuild => 0,
  106. },
  107. cgi_wrappermode => {
  108. type => "string",
  109. default => '06755',
  110. description => "mode for cgi_wrapper (can safely be made suid)",
  111. safe => 0,
  112. rebuild => 0,
  113. },
  114. rcs => {
  115. type => "string",
  116. default => '',
  117. description => "rcs backend to use",
  118. safe => 0, # don't allow overriding
  119. rebuild => 0,
  120. },
  121. default_plugins => {
  122. type => "internal",
  123. default => [qw{mdwn link inline meta htmlscrubber passwordauth
  124. openid signinedit lockedit conditional
  125. recentchanges parentlinks editpage}],
  126. description => "plugins to enable by default",
  127. safe => 0,
  128. rebuild => 1,
  129. },
  130. add_plugins => {
  131. type => "string",
  132. default => [],
  133. description => "plugins to add to the default configuration",
  134. safe => 1,
  135. rebuild => 1,
  136. },
  137. disable_plugins => {
  138. type => "string",
  139. default => [],
  140. description => "plugins to disable",
  141. safe => 1,
  142. rebuild => 1,
  143. },
  144. templatedir => {
  145. type => "string",
  146. default => "$installdir/share/ikiwiki/templates",
  147. description => "additional directory to search for template files",
  148. advanced => 1,
  149. safe => 0, # path
  150. rebuild => 1,
  151. },
  152. underlaydir => {
  153. type => "string",
  154. default => "$installdir/share/ikiwiki/basewiki",
  155. description => "base wiki source location",
  156. advanced => 1,
  157. safe => 0, # path
  158. rebuild => 0,
  159. },
  160. underlaydirbase => {
  161. type => "internal",
  162. default => "$installdir/share/ikiwiki",
  163. description => "parent directory containing additional underlays",
  164. safe => 0,
  165. rebuild => 0,
  166. },
  167. wrappers => {
  168. type => "internal",
  169. default => [],
  170. description => "wrappers to generate",
  171. safe => 0,
  172. rebuild => 0,
  173. },
  174. underlaydirs => {
  175. type => "internal",
  176. default => [],
  177. description => "additional underlays to use",
  178. safe => 0,
  179. rebuild => 0,
  180. },
  181. verbose => {
  182. type => "boolean",
  183. example => 1,
  184. description => "display verbose messages?",
  185. safe => 1,
  186. rebuild => 0,
  187. },
  188. syslog => {
  189. type => "boolean",
  190. example => 1,
  191. description => "log to syslog?",
  192. safe => 1,
  193. rebuild => 0,
  194. },
  195. usedirs => {
  196. type => "boolean",
  197. default => 1,
  198. description => "create output files named page/index.html?",
  199. safe => 0, # changing requires manual transition
  200. rebuild => 1,
  201. },
  202. prefix_directives => {
  203. type => "boolean",
  204. default => 1,
  205. description => "use '!'-prefixed preprocessor directives?",
  206. safe => 0, # changing requires manual transition
  207. rebuild => 1,
  208. },
  209. indexpages => {
  210. type => "boolean",
  211. default => 0,
  212. description => "use page/index.mdwn source files",
  213. safe => 1,
  214. rebuild => 1,
  215. },
  216. discussion => {
  217. type => "boolean",
  218. default => 1,
  219. description => "enable Discussion pages?",
  220. safe => 1,
  221. rebuild => 1,
  222. },
  223. discussionpage => {
  224. type => "string",
  225. default => gettext("Discussion"),
  226. description => "name of Discussion pages",
  227. safe => 1,
  228. rebuild => 1,
  229. },
  230. html5 => {
  231. type => "boolean",
  232. default => 0,
  233. description => "generate HTML5? (experimental)",
  234. advanced => 1,
  235. safe => 1,
  236. rebuild => 1,
  237. },
  238. sslcookie => {
  239. type => "boolean",
  240. default => 0,
  241. description => "only send cookies over SSL connections?",
  242. advanced => 1,
  243. safe => 1,
  244. rebuild => 0,
  245. },
  246. default_pageext => {
  247. type => "string",
  248. default => "mdwn",
  249. description => "extension to use for new pages",
  250. safe => 0, # not sanitized
  251. rebuild => 0,
  252. },
  253. htmlext => {
  254. type => "string",
  255. default => "html",
  256. description => "extension to use for html files",
  257. safe => 0, # not sanitized
  258. rebuild => 1,
  259. },
  260. timeformat => {
  261. type => "string",
  262. default => '%c',
  263. description => "strftime format string to display date",
  264. advanced => 1,
  265. safe => 1,
  266. rebuild => 1,
  267. },
  268. locale => {
  269. type => "string",
  270. default => undef,
  271. example => "en_US.UTF-8",
  272. description => "UTF-8 locale to use",
  273. advanced => 1,
  274. safe => 0,
  275. rebuild => 1,
  276. },
  277. userdir => {
  278. type => "string",
  279. default => "",
  280. example => "users",
  281. description => "put user pages below specified page",
  282. safe => 1,
  283. rebuild => 1,
  284. },
  285. numbacklinks => {
  286. type => "integer",
  287. default => 10,
  288. description => "how many backlinks to show before hiding excess (0 to show all)",
  289. safe => 1,
  290. rebuild => 1,
  291. },
  292. hardlink => {
  293. type => "boolean",
  294. default => 0,
  295. description => "attempt to hardlink source files? (optimisation for large files)",
  296. advanced => 1,
  297. safe => 0, # paranoia
  298. rebuild => 0,
  299. },
  300. umask => {
  301. type => "integer",
  302. example => "022",
  303. description => "force ikiwiki to use a particular umask",
  304. advanced => 1,
  305. safe => 0, # paranoia
  306. rebuild => 0,
  307. },
  308. wrappergroup => {
  309. type => "string",
  310. example => "ikiwiki",
  311. description => "group for wrappers to run in",
  312. advanced => 1,
  313. safe => 0, # paranoia
  314. rebuild => 0,
  315. },
  316. libdir => {
  317. type => "string",
  318. default => "",
  319. example => "$ENV{HOME}/.ikiwiki/",
  320. description => "extra library and plugin directory",
  321. advanced => 1,
  322. safe => 0, # directory
  323. rebuild => 0,
  324. },
  325. ENV => {
  326. type => "string",
  327. default => {},
  328. description => "environment variables",
  329. safe => 0, # paranoia
  330. rebuild => 0,
  331. },
  332. timezone => {
  333. type => "string",
  334. default => "",
  335. example => "US/Eastern",
  336. description => "time zone name",
  337. safe => 1,
  338. rebuild => 1,
  339. },
  340. include => {
  341. type => "string",
  342. default => undef,
  343. example => '^\.htaccess$',
  344. description => "regexp of normally excluded files to include",
  345. advanced => 1,
  346. safe => 0, # regexp
  347. rebuild => 1,
  348. },
  349. exclude => {
  350. type => "string",
  351. default => undef,
  352. example => '^(*\.private|Makefile)$',
  353. description => "regexp of files that should be skipped",
  354. advanced => 1,
  355. safe => 0, # regexp
  356. rebuild => 1,
  357. },
  358. wiki_file_prune_regexps => {
  359. type => "internal",
  360. default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
  361. qr/\.x?html?$/, qr/\.ikiwiki-new$/,
  362. qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
  363. qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
  364. qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
  365. description => "regexps of source files to ignore",
  366. safe => 0,
  367. rebuild => 1,
  368. },
  369. wiki_file_chars => {
  370. type => "string",
  371. description => "specifies the characters that are allowed in source filenames",
  372. default => "-[:alnum:]+/.:_",
  373. safe => 0,
  374. rebuild => 1,
  375. },
  376. wiki_file_regexp => {
  377. type => "internal",
  378. description => "regexp of legal source files",
  379. safe => 0,
  380. rebuild => 1,
  381. },
  382. web_commit_regexp => {
  383. type => "internal",
  384. default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
  385. description => "regexp to parse web commits from logs",
  386. safe => 0,
  387. rebuild => 0,
  388. },
  389. cgi => {
  390. type => "internal",
  391. default => 0,
  392. description => "run as a cgi",
  393. safe => 0,
  394. rebuild => 0,
  395. },
  396. cgi_disable_uploads => {
  397. type => "internal",
  398. default => 1,
  399. description => "whether CGI should accept file uploads",
  400. safe => 0,
  401. rebuild => 0,
  402. },
  403. post_commit => {
  404. type => "internal",
  405. default => 0,
  406. description => "run as a post-commit hook",
  407. safe => 0,
  408. rebuild => 0,
  409. },
  410. rebuild => {
  411. type => "internal",
  412. default => 0,
  413. description => "running in rebuild mode",
  414. safe => 0,
  415. rebuild => 0,
  416. },
  417. setup => {
  418. type => "internal",
  419. default => undef,
  420. description => "running in setup mode",
  421. safe => 0,
  422. rebuild => 0,
  423. },
  424. clean => {
  425. type => "internal",
  426. default => 0,
  427. description => "running in clean mode",
  428. safe => 0,
  429. rebuild => 0,
  430. },
  431. refresh => {
  432. type => "internal",
  433. default => 0,
  434. description => "running in refresh mode",
  435. safe => 0,
  436. rebuild => 0,
  437. },
  438. test_receive => {
  439. type => "internal",
  440. default => 0,
  441. description => "running in receive test mode",
  442. safe => 0,
  443. rebuild => 0,
  444. },
  445. wrapper_background_command => {
  446. type => "internal",
  447. default => '',
  448. description => "background shell command to run",
  449. safe => 0,
  450. rebuild => 0,
  451. },
  452. gettime => {
  453. type => "internal",
  454. description => "running in gettime mode",
  455. safe => 0,
  456. rebuild => 0,
  457. },
  458. w3mmode => {
  459. type => "internal",
  460. default => 0,
  461. description => "running in w3mmode",
  462. safe => 0,
  463. rebuild => 0,
  464. },
  465. wikistatedir => {
  466. type => "internal",
  467. default => undef,
  468. description => "path to the .ikiwiki directory holding ikiwiki state",
  469. safe => 0,
  470. rebuild => 0,
  471. },
  472. setupfile => {
  473. type => "internal",
  474. default => undef,
  475. description => "path to setup file",
  476. safe => 0,
  477. rebuild => 0,
  478. },
  479. setuptype => {
  480. type => "internal",
  481. default => "Standard",
  482. description => "perl class to use to dump setup file",
  483. safe => 0,
  484. rebuild => 0,
  485. },
  486. allow_symlinks_before_srcdir => {
  487. type => "boolean",
  488. default => 0,
  489. description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
  490. safe => 0,
  491. rebuild => 0,
  492. },
  493. }
  494. sub defaultconfig () {
  495. my %s=getsetup();
  496. my @ret;
  497. foreach my $key (keys %s) {
  498. push @ret, $key, $s{$key}->{default};
  499. }
  500. use Data::Dumper;
  501. return @ret;
  502. }
  503. # URL to top of wiki as a path starting with /, valid from any wiki page or
  504. # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
  505. my $local_url;
  506. # URL to CGI script, similar to $local_url
  507. my $local_cgiurl;
  508. sub checkconfig () {
  509. # locale stuff; avoid LC_ALL since it overrides everything
  510. if (defined $ENV{LC_ALL}) {
  511. $ENV{LANG} = $ENV{LC_ALL};
  512. delete $ENV{LC_ALL};
  513. }
  514. if (defined $config{locale}) {
  515. if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
  516. $ENV{LANG}=$config{locale};
  517. define_gettext();
  518. }
  519. }
  520. if (! defined $config{wiki_file_regexp}) {
  521. $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
  522. }
  523. if (ref $config{ENV} eq 'HASH') {
  524. foreach my $val (keys %{$config{ENV}}) {
  525. $ENV{$val}=$config{ENV}{$val};
  526. }
  527. }
  528. if (defined $config{timezone} && length $config{timezone}) {
  529. $ENV{TZ}=$config{timezone};
  530. }
  531. else {
  532. $config{timezone}=$ENV{TZ};
  533. }
  534. if ($config{w3mmode}) {
  535. eval q{use Cwd q{abs_path}};
  536. error($@) if $@;
  537. $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
  538. $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
  539. $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
  540. unless $config{cgiurl} =~ m!file:///!;
  541. $config{url}="file://".$config{destdir};
  542. }
  543. if ($config{cgi} && ! length $config{url}) {
  544. error(gettext("Must specify url to wiki with --url when using --cgi"));
  545. }
  546. if (defined $config{url} && length $config{url}) {
  547. eval q{use URI};
  548. my $baseurl = URI->new($config{url});
  549. $local_url = $baseurl->path . "/";
  550. $local_cgiurl = undef;
  551. if (length $config{cgiurl}) {
  552. my $cgiurl = URI->new($config{cgiurl});
  553. $local_cgiurl = $cgiurl->path;
  554. if ($cgiurl->scheme ne $baseurl->scheme or
  555. $cgiurl->authority ne $baseurl->authority) {
  556. # too far apart, fall back to absolute URLs
  557. $local_url = "$config{url}/";
  558. $local_cgiurl = $config{cgiurl};
  559. }
  560. }
  561. $local_url =~ s{//$}{/};
  562. }
  563. else {
  564. $local_cgiurl = $config{cgiurl};
  565. }
  566. $config{wikistatedir}="$config{srcdir}/.ikiwiki"
  567. unless exists $config{wikistatedir} && defined $config{wikistatedir};
  568. if (defined $config{umask}) {
  569. umask(possibly_foolish_untaint($config{umask}));
  570. }
  571. run_hooks(checkconfig => sub { shift->() });
  572. return 1;
  573. }
  574. sub listplugins () {
  575. my %ret;
  576. foreach my $dir (@INC, $config{libdir}) {
  577. next unless defined $dir && length $dir;
  578. foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
  579. my ($plugin)=$file=~/.*\/(.*)\.pm$/;
  580. $ret{$plugin}=1;
  581. }
  582. }
  583. foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
  584. next unless defined $dir && length $dir;
  585. foreach my $file (glob("$dir/plugins/*")) {
  586. $ret{basename($file)}=1 if -x $file;
  587. }
  588. }
  589. return keys %ret;
  590. }
  591. sub loadplugins () {
  592. if (defined $config{libdir} && length $config{libdir}) {
  593. unshift @INC, possibly_foolish_untaint($config{libdir});
  594. }
  595. foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
  596. loadplugin($plugin);
  597. }
  598. if ($config{rcs}) {
  599. if (exists $hooks{rcs}) {
  600. error(gettext("cannot use multiple rcs plugins"));
  601. }
  602. loadplugin($config{rcs});
  603. }
  604. if (! exists $hooks{rcs}) {
  605. loadplugin("norcs");
  606. }
  607. run_hooks(getopt => sub { shift->() });
  608. if (grep /^-/, @ARGV) {
  609. print STDERR "Unknown option (or missing parameter): $_\n"
  610. foreach grep /^-/, @ARGV;
  611. usage();
  612. }
  613. return 1;
  614. }
  615. sub loadplugin ($;$) {
  616. my $plugin=shift;
  617. my $force=shift;
  618. return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
  619. foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
  620. "$installdir/lib/ikiwiki") {
  621. if (defined $dir && -x "$dir/plugins/$plugin") {
  622. eval { require IkiWiki::Plugin::external };
  623. if ($@) {
  624. my $reason=$@;
  625. error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
  626. }
  627. import IkiWiki::Plugin::external "$dir/plugins/$plugin";
  628. $loaded_plugins{$plugin}=1;
  629. return 1;
  630. }
  631. }
  632. my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
  633. eval qq{use $mod};
  634. if ($@) {
  635. error("Failed to load plugin $mod: $@");
  636. }
  637. $loaded_plugins{$plugin}=1;
  638. return 1;
  639. }
  640. sub error ($;$) {
  641. my $message=shift;
  642. my $cleaner=shift;
  643. log_message('err' => $message) if $config{syslog};
  644. if (defined $cleaner) {
  645. $cleaner->();
  646. }
  647. die $message."\n";
  648. }
  649. sub debug ($) {
  650. return unless $config{verbose};
  651. return log_message(debug => @_);
  652. }
  653. my $log_open=0;
  654. sub log_message ($$) {
  655. my $type=shift;
  656. if ($config{syslog}) {
  657. require Sys::Syslog;
  658. if (! $log_open) {
  659. Sys::Syslog::setlogsock('unix');
  660. Sys::Syslog::openlog('ikiwiki', '', 'user');
  661. $log_open=1;
  662. }
  663. return eval {
  664. Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
  665. };
  666. }
  667. elsif (! $config{cgi}) {
  668. return print "@_\n";
  669. }
  670. else {
  671. return print STDERR "@_\n";
  672. }
  673. }
  674. sub possibly_foolish_untaint ($) {
  675. my $tainted=shift;
  676. my ($untainted)=$tainted=~/(.*)/s;
  677. return $untainted;
  678. }
  679. sub basename ($) {
  680. my $file=shift;
  681. $file=~s!.*/+!!;
  682. return $file;
  683. }
  684. sub dirname ($) {
  685. my $file=shift;
  686. $file=~s!/*[^/]+$!!;
  687. return $file;
  688. }
  689. sub isinternal ($) {
  690. my $page=shift;
  691. return exists $pagesources{$page} &&
  692. $pagesources{$page} =~ /\._([^.]+)$/;
  693. }
  694. sub pagetype ($) {
  695. my $file=shift;
  696. if ($file =~ /\.([^.]+)$/) {
  697. return $1 if exists $hooks{htmlize}{$1};
  698. }
  699. my $base=basename($file);
  700. if (exists $hooks{htmlize}{$base} &&
  701. $hooks{htmlize}{$base}{noextension}) {
  702. return $base;
  703. }
  704. return;
  705. }
  706. my %pagename_cache;
  707. sub pagename ($) {
  708. my $file=shift;
  709. if (exists $pagename_cache{$file}) {
  710. return $pagename_cache{$file};
  711. }
  712. my $type=pagetype($file);
  713. my $page=$file;
  714. $page=~s/\Q.$type\E*$//
  715. if defined $type && !$hooks{htmlize}{$type}{keepextension}
  716. && !$hooks{htmlize}{$type}{noextension};
  717. if ($config{indexpages} && $page=~/(.*)\/index$/) {
  718. $page=$1;
  719. }
  720. $pagename_cache{$file} = $page;
  721. return $page;
  722. }
  723. sub newpagefile ($$) {
  724. my $page=shift;
  725. my $type=shift;
  726. if (! $config{indexpages} || $page eq 'index') {
  727. return $page.".".$type;
  728. }
  729. else {
  730. return $page."/index.".$type;
  731. }
  732. }
  733. sub targetpage ($$;$) {
  734. my $page=shift;
  735. my $ext=shift;
  736. my $filename=shift;
  737. if (defined $filename) {
  738. return $page."/".$filename.".".$ext;
  739. }
  740. elsif (! $config{usedirs} || $page eq 'index') {
  741. return $page.".".$ext;
  742. }
  743. else {
  744. return $page."/index.".$ext;
  745. }
  746. }
  747. sub htmlpage ($) {
  748. my $page=shift;
  749. return targetpage($page, $config{htmlext});
  750. }
  751. sub srcfile_stat {
  752. my $file=shift;
  753. my $nothrow=shift;
  754. return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
  755. foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
  756. return "$dir/$file", stat(_) if -e "$dir/$file";
  757. }
  758. error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
  759. return;
  760. }
  761. sub srcfile ($;$) {
  762. return (srcfile_stat(@_))[0];
  763. }
  764. sub add_literal_underlay ($) {
  765. my $dir=shift;
  766. if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
  767. unshift @{$config{underlaydirs}}, $dir;
  768. }
  769. }
  770. sub add_underlay ($) {
  771. my $dir = shift;
  772. if ($dir !~ /^\//) {
  773. $dir="$config{underlaydirbase}/$dir";
  774. }
  775. add_literal_underlay($dir);
  776. # why does it return 1? we just don't know
  777. return 1;
  778. }
  779. sub readfile ($;$$) {
  780. my $file=shift;
  781. my $binary=shift;
  782. my $wantfd=shift;
  783. if (-l $file) {
  784. error("cannot read a symlink ($file)");
  785. }
  786. local $/=undef;
  787. open (my $in, "<", $file) || error("failed to read $file: $!");
  788. binmode($in) if ($binary);
  789. return \*$in if $wantfd;
  790. my $ret=<$in>;
  791. # check for invalid utf-8, and toss it back to avoid crashes
  792. if (! utf8::valid($ret)) {
  793. $ret=encode_utf8($ret);
  794. }
  795. close $in || error("failed to read $file: $!");
  796. return $ret;
  797. }
  798. sub prep_writefile ($$) {
  799. my $file=shift;
  800. my $destdir=shift;
  801. my $test=$file;
  802. while (length $test) {
  803. if (-l "$destdir/$test") {
  804. error("cannot write to a symlink ($test)");
  805. }
  806. if (-f _ && $test ne $file) {
  807. # Remove conflicting file.
  808. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  809. foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  810. if ($f eq $test) {
  811. unlink("$destdir/$test");
  812. last;
  813. }
  814. }
  815. }
  816. }
  817. $test=dirname($test);
  818. }
  819. my $dir=dirname("$destdir/$file");
  820. if (! -d $dir) {
  821. my $d="";
  822. foreach my $s (split(m!/+!, $dir)) {
  823. $d.="$s/";
  824. if (! -d $d) {
  825. mkdir($d) || error("failed to create directory $d: $!");
  826. }
  827. }
  828. }
  829. return 1;
  830. }
  831. sub writefile ($$$;$$) {
  832. my $file=shift; # can include subdirs
  833. my $destdir=shift; # directory to put file in
  834. my $content=shift;
  835. my $binary=shift;
  836. my $writer=shift;
  837. prep_writefile($file, $destdir);
  838. my $newfile="$destdir/$file.ikiwiki-new";
  839. if (-l $newfile) {
  840. error("cannot write to a symlink ($newfile)");
  841. }
  842. my $cleanup = sub { unlink($newfile) };
  843. open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
  844. binmode($out) if ($binary);
  845. if ($writer) {
  846. $writer->(\*$out, $cleanup);
  847. }
  848. else {
  849. print $out $content or error("failed writing to $newfile: $!", $cleanup);
  850. }
  851. close $out || error("failed saving $newfile: $!", $cleanup);
  852. rename($newfile, "$destdir/$file") ||
  853. error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
  854. return 1;
  855. }
  856. my %cleared;
  857. sub will_render ($$;$) {
  858. my $page=shift;
  859. my $dest=shift;
  860. my $clear=shift;
  861. # Important security check for independently created files.
  862. if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
  863. ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
  864. my $from_other_page=0;
  865. # Expensive, but rarely runs.
  866. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  867. if (grep {
  868. $_ eq $dest ||
  869. dirname($_) eq $dest
  870. } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  871. $from_other_page=1;
  872. last;
  873. }
  874. }
  875. error("$config{destdir}/$dest independently created, not overwriting with version from $page")
  876. unless $from_other_page;
  877. }
  878. # If $dest exists as a directory, remove conflicting files in it
  879. # rendered from other pages.
  880. if (-d _) {
  881. foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
  882. foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
  883. if (dirname($f) eq $dest) {
  884. unlink("$config{destdir}/$f");
  885. rmdir(dirname("$config{destdir}/$f"));
  886. }
  887. }
  888. }
  889. }
  890. if (! $clear || $cleared{$page}) {
  891. $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
  892. }
  893. else {
  894. foreach my $old (@{$renderedfiles{$page}}) {
  895. delete $destsources{$old};
  896. }
  897. $renderedfiles{$page}=[$dest];
  898. $cleared{$page}=1;
  899. }
  900. $destsources{$dest}=$page;
  901. return 1;
  902. }
  903. sub bestlink ($$) {
  904. my $page=shift;
  905. my $link=shift;
  906. my $cwd=$page;
  907. if ($link=~s/^\/+//) {
  908. # absolute links
  909. $cwd="";
  910. }
  911. $link=~s/\/$//;
  912. do {
  913. my $l=$cwd;
  914. $l.="/" if length $l;
  915. $l.=$link;
  916. if (exists $pagesources{$l}) {
  917. return $l;
  918. }
  919. elsif (exists $pagecase{lc $l}) {
  920. return $pagecase{lc $l};
  921. }
  922. } while $cwd=~s{/?[^/]+$}{};
  923. if (length $config{userdir}) {
  924. my $l = "$config{userdir}/".lc($link);
  925. if (exists $pagesources{$l}) {
  926. return $l;
  927. }
  928. elsif (exists $pagecase{lc $l}) {
  929. return $pagecase{lc $l};
  930. }
  931. }
  932. #print STDERR "warning: page $page, broken link: $link\n";
  933. return "";
  934. }
  935. sub isinlinableimage ($) {
  936. my $file=shift;
  937. return $file =~ /\.(png|gif|jpg|jpeg)$/i;
  938. }
  939. sub pagetitle ($;$) {
  940. my $page=shift;
  941. my $unescaped=shift;
  942. if ($unescaped) {
  943. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
  944. }
  945. else {
  946. $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
  947. }
  948. return $page;
  949. }
  950. sub titlepage ($) {
  951. my $title=shift;
  952. # support use w/o %config set
  953. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  954. $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  955. return $title;
  956. }
  957. sub linkpage ($) {
  958. my $link=shift;
  959. my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
  960. $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
  961. return $link;
  962. }
  963. sub cgiurl (@) {
  964. my %params=@_;
  965. my $cgiurl=$local_cgiurl;
  966. if (exists $params{cgiurl}) {
  967. $cgiurl=$params{cgiurl};
  968. delete $params{cgiurl};
  969. }
  970. unless (%params) {
  971. return $cgiurl;
  972. }
  973. return $cgiurl."?".
  974. join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
  975. }
  976. sub baseurl (;$) {
  977. my $page=shift;
  978. return $local_url if ! defined $page;
  979. $page=htmlpage($page);
  980. $page=~s/[^\/]+$//;
  981. $page=~s/[^\/]+\//..\//g;
  982. return $page;
  983. }
  984. sub urlabs ($$) {
  985. my $url=shift;
  986. my $urlbase=shift;
  987. return $url unless defined $urlbase && length $urlbase;
  988. eval q{use URI};
  989. URI->new_abs($url, $urlbase)->as_string;
  990. }
  991. sub abs2rel ($$) {
  992. # Work around very innefficient behavior in File::Spec if abs2rel
  993. # is passed two relative paths. It's much faster if paths are
  994. # absolute! (Debian bug #376658; fixed in debian unstable now)
  995. my $path="/".shift;
  996. my $base="/".shift;
  997. require File::Spec;
  998. my $ret=File::Spec->abs2rel($path, $base);
  999. $ret=~s/^// if defined $ret;
  1000. return $ret;
  1001. }
  1002. sub displaytime ($;$$) {
  1003. # Plugins can override this function to mark up the time to
  1004. # display.
  1005. my $time=formattime($_[0], $_[1]);
  1006. if ($config{html5}) {
  1007. return '<time datetime="'.date_3339($_[0]).'"'.
  1008. ($_[2] ? ' pubdate="pubdate"' : '').
  1009. '>'.$time.'</time>';
  1010. }
  1011. else {
  1012. return '<span class="date">'.$time.'</span>';
  1013. }
  1014. }
  1015. sub formattime ($;$) {
  1016. # Plugins can override this function to format the time.
  1017. my $time=shift;
  1018. my $format=shift;
  1019. if (! defined $format) {
  1020. $format=$config{timeformat};
  1021. }
  1022. # strftime doesn't know about encodings, so make sure
  1023. # its output is properly treated as utf8
  1024. return decode_utf8(POSIX::strftime($format, localtime($time)));
  1025. }
  1026. sub date_3339 ($) {
  1027. my $time=shift;
  1028. my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
  1029. POSIX::setlocale(&POSIX::LC_TIME, "C");
  1030. my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
  1031. POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
  1032. return $ret;
  1033. }
  1034. sub beautify_urlpath ($) {
  1035. my $url=shift;
  1036. # Ensure url is not an empty link, and if necessary,
  1037. # add ./ to avoid colon confusion.
  1038. if ($url !~ /^\// && $url !~ /^\.\.?\//) {
  1039. $url="./$url";
  1040. }
  1041. if ($config{usedirs}) {
  1042. $url =~ s!/index.$config{htmlext}$!/!;
  1043. }
  1044. return $url;
  1045. }
  1046. sub urlto ($;$$) {
  1047. my $to=shift;
  1048. my $from=shift;
  1049. my $absolute=shift;
  1050. if (! length $to) {
  1051. $to = 'index';
  1052. }
  1053. if (! $destsources{$to}) {
  1054. $to=htmlpage($to);
  1055. }
  1056. if ($absolute) {
  1057. return $config{url}.beautify_urlpath("/".$to);
  1058. }
  1059. if (! defined $from) {
  1060. my $u = $local_url || '';
  1061. $u =~ s{/$}{};
  1062. return $u.beautify_urlpath("/".$to);
  1063. }
  1064. my $link = abs2rel($to, dirname(htmlpage($from)));
  1065. return beautify_urlpath($link);
  1066. }
  1067. sub isselflink ($$) {
  1068. # Plugins can override this function to support special types
  1069. # of selflinks.
  1070. my $page=shift;
  1071. my $link=shift;
  1072. return $page eq $link;
  1073. }
  1074. sub htmllink ($$$;@) {
  1075. my $lpage=shift; # the page doing the linking
  1076. my $page=shift; # the page that will contain the link (different for inline)
  1077. my $link=shift;
  1078. my %opts=@_;
  1079. $link=~s/\/$//;
  1080. my $bestlink;
  1081. if (! $opts{forcesubpage}) {
  1082. $bestlink=bestlink($lpage, $link);
  1083. }
  1084. else {
  1085. $bestlink="$lpage/".lc($link);
  1086. }
  1087. my $linktext;
  1088. if (defined $opts{linktext}) {
  1089. $linktext=$opts{linktext};
  1090. }
  1091. else {
  1092. $linktext=pagetitle(basename($link));
  1093. }
  1094. return "<span class=\"selflink\">$linktext</span>"
  1095. if length $bestlink && isselflink($page, $bestlink) &&
  1096. ! defined $opts{anchor};
  1097. if (! $destsources{$bestlink}) {
  1098. $bestlink=htmlpage($bestlink);
  1099. if (! $destsources{$bestlink}) {
  1100. my $cgilink = "";
  1101. if (length $config{cgiurl}) {
  1102. $cgilink = "<a href=\"".
  1103. cgiurl(
  1104. do => "create",
  1105. page => lc($link),
  1106. from => $lpage
  1107. )."\" rel=\"nofollow\">?</a>";
  1108. }
  1109. return "<span class=\"createlink\">$cgilink$linktext</span>"
  1110. }
  1111. }
  1112. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  1113. $bestlink=beautify_urlpath($bestlink);
  1114. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  1115. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  1116. }
  1117. if (defined $opts{anchor}) {
  1118. $bestlink.="#".$opts{anchor};
  1119. }
  1120. my @attrs;
  1121. foreach my $attr (qw{rel class title}) {
  1122. if (defined $opts{$attr}) {
  1123. push @attrs, " $attr=\"$opts{$attr}\"";
  1124. }
  1125. }
  1126. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  1127. }
  1128. sub userpage ($) {
  1129. my $user=shift;
  1130. return length $config{userdir} ? "$config{userdir}/$user" : $user;
  1131. }
  1132. sub openiduser ($) {
  1133. my $user=shift;
  1134. if (defined $user && $user =~ m!^https?://! &&
  1135. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  1136. my $display;
  1137. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  1138. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  1139. }
  1140. else {
  1141. # backcompat with old version
  1142. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  1143. $display=$oid->display;
  1144. }
  1145. # Convert "user.somehost.com" to "user [somehost.com]"
  1146. # (also "user.somehost.co.uk")
  1147. if ($display !~ /\[/) {
  1148. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  1149. }
  1150. # Convert "http://somehost.com/user" to "user [somehost.com]".
  1151. # (also "https://somehost.com/user/")
  1152. if ($display !~ /\[/) {
  1153. $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
  1154. }
  1155. $display=~s!^https?://!!; # make sure this is removed
  1156. eval q{use CGI 'escapeHTML'};
  1157. error($@) if $@;
  1158. return escapeHTML($display);
  1159. }
  1160. return;
  1161. }
  1162. sub htmlize ($$$$) {
  1163. my $page=shift;
  1164. my $destpage=shift;
  1165. my $type=shift;
  1166. my $content=shift;
  1167. my $oneline = $content !~ /\n/;
  1168. if (exists $hooks{htmlize}{$type}) {
  1169. $content=$hooks{htmlize}{$type}{call}->(
  1170. page => $page,
  1171. content => $content,
  1172. );
  1173. }
  1174. else {
  1175. error("htmlization of $type not supported");
  1176. }
  1177. run_hooks(sanitize => sub {
  1178. $content=shift->(
  1179. page => $page,
  1180. destpage => $destpage,
  1181. content => $content,
  1182. );
  1183. });
  1184. if ($oneline) {
  1185. # hack to get rid of enclosing junk added by markdown
  1186. # and other htmlizers/sanitizers
  1187. $content=~s/^<p>//i;
  1188. $content=~s/<\/p>\n*$//i;
  1189. }
  1190. return $content;
  1191. }
  1192. sub linkify ($$$) {
  1193. my $page=shift;
  1194. my $destpage=shift;
  1195. my $content=shift;
  1196. run_hooks(linkify => sub {
  1197. $content=shift->(
  1198. page => $page,
  1199. destpage => $destpage,
  1200. content => $content,
  1201. );
  1202. });
  1203. return $content;
  1204. }
  1205. our %preprocessing;
  1206. our $preprocess_preview=0;
  1207. sub preprocess ($$$;$$) {
  1208. my $page=shift; # the page the data comes from
  1209. my $destpage=shift; # the page the data will appear in (different for inline)
  1210. my $content=shift;
  1211. my $scan=shift;
  1212. my $preview=shift;
  1213. # Using local because it needs to be set within any nested calls
  1214. # of this function.
  1215. local $preprocess_preview=$preview if defined $preview;
  1216. my $handle=sub {
  1217. my $escape=shift;
  1218. my $prefix=shift;
  1219. my $command=shift;
  1220. my $params=shift;
  1221. $params="" if ! defined $params;
  1222. if (length $escape) {
  1223. return "[[$prefix$command $params]]";
  1224. }
  1225. elsif (exists $hooks{preprocess}{$command}) {
  1226. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1227. # Note: preserve order of params, some plugins may
  1228. # consider it significant.
  1229. my @params;
  1230. while ($params =~ m{
  1231. (?:([-\w]+)=)? # 1: named parameter key?
  1232. (?:
  1233. """(.*?)""" # 2: triple-quoted value
  1234. |
  1235. "([^"]*?)" # 3: single-quoted value
  1236. |
  1237. (\S+) # 4: unquoted value
  1238. )
  1239. (?:\s+|$) # delimiter to next param
  1240. }sgx) {
  1241. my $key=$1;
  1242. my $val;
  1243. if (defined $2) {
  1244. $val=$2;
  1245. $val=~s/\r\n/\n/mg;
  1246. $val=~s/^\n+//g;
  1247. $val=~s/\n+$//g;
  1248. }
  1249. elsif (defined $3) {
  1250. $val=$3;
  1251. }
  1252. elsif (defined $4) {
  1253. $val=$4;
  1254. }
  1255. if (defined $key) {
  1256. push @params, $key, $val;
  1257. }
  1258. else {
  1259. push @params, $val, '';
  1260. }
  1261. }
  1262. if ($preprocessing{$page}++ > 3) {
  1263. # Avoid loops of preprocessed pages preprocessing
  1264. # other pages that preprocess them, etc.
  1265. return "[[!$command <span class=\"error\">".
  1266. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1267. $page, $preprocessing{$page}).
  1268. "</span>]]";
  1269. }
  1270. my $ret;
  1271. if (! $scan) {
  1272. $ret=eval {
  1273. $hooks{preprocess}{$command}{call}->(
  1274. @params,
  1275. page => $page,
  1276. destpage => $destpage,
  1277. preview => $preprocess_preview,
  1278. );
  1279. };
  1280. if ($@) {
  1281. my $error=$@;
  1282. chomp $error;
  1283. $ret="[[!$command <span class=\"error\">".
  1284. gettext("Error").": $error"."</span>]]";
  1285. }
  1286. }
  1287. else {
  1288. # use void context during scan pass
  1289. eval {
  1290. $hooks{preprocess}{$command}{call}->(
  1291. @params,
  1292. page => $page,
  1293. destpage => $destpage,
  1294. preview => $preprocess_preview,
  1295. );
  1296. };
  1297. $ret="";
  1298. }
  1299. $preprocessing{$page}--;
  1300. return $ret;
  1301. }
  1302. else {
  1303. return "[[$prefix$command $params]]";
  1304. }
  1305. };
  1306. my $regex;
  1307. if ($config{prefix_directives}) {
  1308. $regex = qr{
  1309. (\\?) # 1: escape?
  1310. \[\[(!) # directive open; 2: prefix
  1311. ([-\w]+) # 3: command
  1312. ( # 4: the parameters..
  1313. \s+ # Must have space if parameters present
  1314. (?:
  1315. (?:[-\w]+=)? # named parameter key?
  1316. (?:
  1317. """.*?""" # triple-quoted value
  1318. |
  1319. "[^"]*?" # single-quoted value
  1320. |
  1321. [^"\s\]]+ # unquoted value
  1322. )
  1323. \s* # whitespace or end
  1324. # of directive
  1325. )
  1326. *)? # 0 or more parameters
  1327. \]\] # directive closed
  1328. }sx;
  1329. }
  1330. else {
  1331. $regex = qr{
  1332. (\\?) # 1: escape?
  1333. \[\[(!?) # directive open; 2: optional prefix
  1334. ([-\w]+) # 3: command
  1335. \s+
  1336. ( # 4: the parameters..
  1337. (?:
  1338. (?:[-\w]+=)? # named parameter key?
  1339. (?:
  1340. """.*?""" # triple-quoted value
  1341. |
  1342. "[^"]*?" # single-quoted value
  1343. |
  1344. [^"\s\]]+ # unquoted value
  1345. )
  1346. \s* # whitespace or end
  1347. # of directive
  1348. )
  1349. *) # 0 or more parameters
  1350. \]\] # directive closed
  1351. }sx;
  1352. }
  1353. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1354. return $content;
  1355. }
  1356. sub filter ($$$) {
  1357. my $page=shift;
  1358. my $destpage=shift;
  1359. my $content=shift;
  1360. run_hooks(filter => sub {
  1361. $content=shift->(page => $page, destpage => $destpage,
  1362. content => $content);
  1363. });
  1364. return $content;
  1365. }
  1366. sub check_canedit ($$$;$) {
  1367. my $page=shift;
  1368. my $q=shift;
  1369. my $session=shift;
  1370. my $nonfatal=shift;
  1371. my $canedit;
  1372. run_hooks(canedit => sub {
  1373. return if defined $canedit;
  1374. my $ret=shift->($page, $q, $session);
  1375. if (defined $ret) {
  1376. if ($ret eq "") {
  1377. $canedit=1;
  1378. }
  1379. elsif (ref $ret eq 'CODE') {
  1380. $ret->() unless $nonfatal;
  1381. $canedit=0;
  1382. }
  1383. elsif (defined $ret) {
  1384. error($ret) unless $nonfatal;
  1385. $canedit=0;
  1386. }
  1387. }
  1388. });
  1389. return defined $canedit ? $canedit : 1;
  1390. }
  1391. sub check_content (@) {
  1392. my %params=@_;
  1393. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1394. if (exists $pagesources{$params{page}}) {
  1395. my @diff;
  1396. my %old=map { $_ => 1 }
  1397. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1398. foreach my $line (split("\n", $params{content})) {
  1399. push @diff, $line if ! exists $old{$line};
  1400. }
  1401. $params{diff}=join("\n", @diff);
  1402. }
  1403. my $ok;
  1404. run_hooks(checkcontent => sub {
  1405. return if defined $ok;
  1406. my $ret=shift->(%params);
  1407. if (defined $ret) {
  1408. if ($ret eq "") {
  1409. $ok=1;
  1410. }
  1411. elsif (ref $ret eq 'CODE') {
  1412. $ret->() unless $params{nonfatal};
  1413. $ok=0;
  1414. }
  1415. elsif (defined $ret) {
  1416. error($ret) unless $params{nonfatal};
  1417. $ok=0;
  1418. }
  1419. }
  1420. });
  1421. return defined $ok ? $ok : 1;
  1422. }
  1423. sub check_canchange (@) {
  1424. my %params = @_;
  1425. my $cgi = $params{cgi};
  1426. my $session = $params{session};
  1427. my @changes = @{$params{changes}};
  1428. my %newfiles;
  1429. foreach my $change (@changes) {
  1430. # This untaint is safe because we check file_pruned and
  1431. # wiki_file_regexp.
  1432. my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
  1433. $file=possibly_foolish_untaint($file);
  1434. if (! defined $file || ! length $file ||
  1435. file_pruned($file)) {
  1436. error(gettext("bad file name %s"), $file);
  1437. }
  1438. my $type=pagetype($file);
  1439. my $page=pagename($file) if defined $type;
  1440. if ($change->{action} eq 'add') {
  1441. $newfiles{$file}=1;
  1442. }
  1443. if ($change->{action} eq 'change' ||
  1444. $change->{action} eq 'add') {
  1445. if (defined $page) {
  1446. check_canedit($page, $cgi, $session);
  1447. next;
  1448. }
  1449. else {
  1450. if (IkiWiki::Plugin::attachment->can("check_canattach")) {
  1451. IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
  1452. check_canedit($file, $cgi, $session);
  1453. next;
  1454. }
  1455. }
  1456. }
  1457. elsif ($change->{action} eq 'remove') {
  1458. # check_canremove tests to see if the file is present
  1459. # on disk. This will fail when a single commit adds a
  1460. # file and then removes it again. Avoid the problem
  1461. # by not testing the removal in such pairs of changes.
  1462. # (The add is still tested, just to make sure that
  1463. # no data is added to the repo that a web edit
  1464. # could not add.)
  1465. next if $newfiles{$file};
  1466. if (IkiWiki::Plugin::remove->can("check_canremove")) {
  1467. IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
  1468. check_canedit(defined $page ? $page : $file, $cgi, $session);
  1469. next;
  1470. }
  1471. }
  1472. else {
  1473. error "unknown action ".$change->{action};
  1474. }
  1475. error sprintf(gettext("you are not allowed to change %s"), $file);
  1476. }
  1477. }
  1478. my $wikilock;
  1479. sub lockwiki () {
  1480. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1481. # run issues. The lock will be dropped on program exit.
  1482. if (! -d $config{wikistatedir}) {
  1483. mkdir($config{wikistatedir});
  1484. }
  1485. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1486. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1487. if (! flock($wikilock, 2)) { # LOCK_EX
  1488. error("failed to get lock");
  1489. }
  1490. return 1;
  1491. }
  1492. sub unlockwiki () {
  1493. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1494. return close($wikilock) if $wikilock;
  1495. return;
  1496. }
  1497. my $commitlock;
  1498. sub commit_hook_enabled () {
  1499. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1500. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1501. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1502. close($commitlock) || error("failed closing commitlock: $!");
  1503. return 0;
  1504. }
  1505. close($commitlock) || error("failed closing commitlock: $!");
  1506. return 1;
  1507. }
  1508. sub disable_commit_hook () {
  1509. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1510. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1511. if (! flock($commitlock, 2)) { # LOCK_EX
  1512. error("failed to get commit lock");
  1513. }
  1514. return 1;
  1515. }
  1516. sub enable_commit_hook () {
  1517. return close($commitlock) if $commitlock;
  1518. return;
  1519. }
  1520. sub loadindex () {
  1521. %oldrenderedfiles=%pagectime=();
  1522. if (! $config{rebuild}) {
  1523. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1524. %destsources=%renderedfiles=%pagecase=%pagestate=
  1525. %depends_simple=%typedlinks=%oldtypedlinks=();
  1526. }
  1527. my $in;
  1528. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1529. if (-e "$config{wikistatedir}/index") {
  1530. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1531. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1532. }
  1533. else {
  1534. $config{gettime}=1; # first build
  1535. return;
  1536. }
  1537. }
  1538. my $index=Storable::fd_retrieve($in);
  1539. if (! defined $index) {
  1540. return 0;
  1541. }
  1542. my $pages;
  1543. if (exists $index->{version} && ! ref $index->{version}) {
  1544. $pages=$index->{page};
  1545. %wikistate=%{$index->{state}};
  1546. # Handle plugins that got disabled by loading a new setup.
  1547. if (exists $config{setupfile}) {
  1548. require IkiWiki::Setup;
  1549. IkiWiki::Setup::disabled_plugins(
  1550. grep { ! $loaded_plugins{$_} } keys %wikistate);
  1551. }
  1552. }
  1553. else {
  1554. $pages=$index;
  1555. %wikistate=();
  1556. }
  1557. foreach my $src (keys %$pages) {
  1558. my $d=$pages->{$src};
  1559. my $page=pagename($src);
  1560. $pagectime{$page}=$d->{ctime};
  1561. $pagesources{$page}=$src;
  1562. if (! $config{rebuild}) {
  1563. $pagemtime{$page}=$d->{mtime};
  1564. $renderedfiles{$page}=$d->{dest};
  1565. if (exists $d->{links} && ref $d->{links}) {
  1566. $links{$page}=$d->{links};
  1567. $oldlinks{$page}=[@{$d->{links}}];
  1568. }
  1569. if (ref $d->{depends_simple} eq 'ARRAY') {
  1570. # old format
  1571. $depends_simple{$page}={
  1572. map { $_ => 1 } @{$d->{depends_simple}}
  1573. };
  1574. }
  1575. elsif (exists $d->{depends_simple}) {
  1576. $depends_simple{$page}=$d->{depends_simple};
  1577. }
  1578. if (exists $d->{dependslist}) {
  1579. # old format
  1580. $depends{$page}={
  1581. map { $_ => $DEPEND_CONTENT }
  1582. @{$d->{dependslist}}
  1583. };
  1584. }
  1585. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1586. # old format
  1587. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1588. }
  1589. elsif (exists $d->{depends}) {
  1590. $depends{$page}=$d->{depends};
  1591. }
  1592. if (exists $d->{state}) {
  1593. $pagestate{$page}=$d->{state};
  1594. }
  1595. if (exists $d->{typedlinks}) {
  1596. $typedlinks{$page}=$d->{typedlinks};
  1597. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1598. next unless %$links;
  1599. $oldtypedlinks{$page}{$type} = {%$links};
  1600. }
  1601. }
  1602. }
  1603. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1604. }
  1605. foreach my $page (keys %pagesources) {
  1606. $pagecase{lc $page}=$page;
  1607. }
  1608. foreach my $page (keys %renderedfiles) {
  1609. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1610. }
  1611. return close($in);
  1612. }
  1613. sub saveindex () {
  1614. run_hooks(savestate => sub { shift->() });
  1615. my @plugins=keys %loaded_plugins;
  1616. if (! -d $config{wikistatedir}) {
  1617. mkdir($config{wikistatedir});
  1618. }
  1619. my $newfile="$config{wikistatedir}/indexdb.new";
  1620. my $cleanup = sub { unlink($newfile) };
  1621. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1622. my %index;
  1623. foreach my $page (keys %pagemtime) {
  1624. next unless $pagemtime{$page};
  1625. my $src=$pagesources{$page};
  1626. $index{page}{$src}={
  1627. ctime => $pagectime{$page},
  1628. mtime => $pagemtime{$page},
  1629. dest => $renderedfiles{$page},
  1630. links => $links{$page},
  1631. };
  1632. if (exists $depends{$page}) {
  1633. $index{page}{$src}{depends} = $depends{$page};
  1634. }
  1635. if (exists $depends_simple{$page}) {
  1636. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1637. }
  1638. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1639. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1640. }
  1641. if (exists $pagestate{$page}) {
  1642. foreach my $id (@plugins) {
  1643. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1644. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1645. }
  1646. }
  1647. }
  1648. }
  1649. $index{state}={};
  1650. foreach my $id (@plugins) {
  1651. $index{state}{$id}={}; # used to detect disabled plugins
  1652. foreach my $key (keys %{$wikistate{$id}}) {
  1653. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1654. }
  1655. }
  1656. $index{version}="3";
  1657. my $ret=Storable::nstore_fd(\%index, $out);
  1658. return if ! defined $ret || ! $ret;
  1659. close $out || error("failed saving to $newfile: $!", $cleanup);
  1660. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1661. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1662. return 1;
  1663. }
  1664. sub template_file ($) {
  1665. my $name=shift;
  1666. my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
  1667. my $template;
  1668. if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
  1669. $template=srcfile($pagesources{$tpage}, 1);
  1670. $name.=".tmpl";
  1671. }
  1672. else {
  1673. $template=srcfile($tpage, 1);
  1674. }
  1675. if (defined $template) {
  1676. return $template, $tpage, 1 if wantarray;
  1677. return $template;
  1678. }
  1679. else {
  1680. $name=~s:/::; # avoid path traversal
  1681. foreach my $dir ($config{templatedir},
  1682. "$installdir/share/ikiwiki/templates") {
  1683. if (-e "$dir/$name") {
  1684. $template="$dir/$name";
  1685. last;
  1686. }
  1687. }
  1688. if (defined $template) {
  1689. return $template, $tpage if wantarray;
  1690. return $template;
  1691. }
  1692. }
  1693. return;
  1694. }
  1695. sub template_depends ($$;@) {
  1696. my $name=shift;
  1697. my $page=shift;
  1698. my ($filename, $tpage, $untrusted)=template_file($name);
  1699. if (! defined $filename) {
  1700. error(sprintf(gettext("template %s not found"), $name))
  1701. }
  1702. if (defined $page && defined $tpage) {
  1703. add_depends($page, $tpage);
  1704. }
  1705. my @opts=(
  1706. filter => sub {
  1707. my $text_ref = shift;
  1708. ${$text_ref} = decode_utf8(${$text_ref});
  1709. },
  1710. loop_context_vars => 1,
  1711. die_on_bad_params => 0,
  1712. parent_global_vars => 1,
  1713. filename => $filename,
  1714. @_,
  1715. ($untrusted ? (no_includes => 1) : ()),
  1716. );
  1717. return @opts if wantarray;
  1718. require HTML::Template;
  1719. return HTML::Template->new(@opts);
  1720. }
  1721. sub template ($;@) {
  1722. template_depends(shift, undef, @_);
  1723. }
  1724. sub templateactions ($$) {
  1725. my $template=shift;
  1726. my $page=shift;
  1727. my $have_actions=0;
  1728. my @actions;
  1729. run_hooks(pageactions => sub {
  1730. push @actions, map { { action => $_ } }
  1731. grep { defined } shift->(page => $page);
  1732. });
  1733. $template->param(actions => \@actions);
  1734. if ($config{cgiurl} && exists $hooks{auth}) {
  1735. $template->param(prefsurl => cgiurl(do => "prefs"));
  1736. $have_actions=1;
  1737. }
  1738. if ($have_actions || @actions) {
  1739. $template->param(have_actions => 1);
  1740. }
  1741. }
  1742. sub hook (@) {
  1743. my %param=@_;
  1744. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1745. error 'hook requires type, call, and id parameters';
  1746. }
  1747. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1748. $hooks{$param{type}}{$param{id}}=\%param;
  1749. return 1;
  1750. }
  1751. sub run_hooks ($$) {
  1752. # Calls the given sub for each hook of the given type,
  1753. # passing it the hook function to call.
  1754. my $type=shift;
  1755. my $sub=shift;
  1756. if (exists $hooks{$type}) {
  1757. my (@first, @middle, @last);
  1758. foreach my $id (keys %{$hooks{$type}}) {
  1759. if ($hooks{$type}{$id}{first}) {
  1760. push @first, $id;
  1761. }
  1762. elsif ($hooks{$type}{$id}{last}) {
  1763. push @last, $id;
  1764. }
  1765. else {
  1766. push @middle, $id;
  1767. }
  1768. }
  1769. foreach my $id (@first, @middle, @last) {
  1770. $sub->($hooks{$type}{$id}{call});
  1771. }
  1772. }
  1773. return 1;
  1774. }
  1775. sub rcs_update () {
  1776. $hooks{rcs}{rcs_update}{call}->(@_);
  1777. }
  1778. sub rcs_prepedit ($) {
  1779. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1780. }
  1781. sub rcs_commit (@) {
  1782. $hooks{rcs}{rcs_commit}{call}->(@_);
  1783. }
  1784. sub rcs_commit_staged (@) {
  1785. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1786. }
  1787. sub rcs_add ($) {
  1788. $hooks{rcs}{rcs_add}{call}->(@_);
  1789. }
  1790. sub rcs_remove ($) {
  1791. $hooks{rcs}{rcs_remove}{call}->(@_);
  1792. }
  1793. sub rcs_rename ($$) {
  1794. $hooks{rcs}{rcs_rename}{call}->(@_);
  1795. }
  1796. sub rcs_recentchanges ($) {
  1797. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1798. }
  1799. sub rcs_diff ($;$) {
  1800. $hooks{rcs}{rcs_diff}{call}->(@_);
  1801. }
  1802. sub rcs_getctime ($) {
  1803. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1804. }
  1805. sub rcs_getmtime ($) {
  1806. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1807. }
  1808. sub rcs_receive () {
  1809. $hooks{rcs}{rcs_receive}{call}->();
  1810. }
  1811. sub add_depends ($$;$) {
  1812. my $page=shift;
  1813. my $pagespec=shift;
  1814. my $deptype=shift || $DEPEND_CONTENT;
  1815. # Is the pagespec a simple page name?
  1816. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1817. $pagespec !~ /[\s*?()!]/) {
  1818. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1819. return 1;
  1820. }
  1821. # Add explicit dependencies for influences.
  1822. my $sub=pagespec_translate($pagespec);
  1823. return unless defined $sub;
  1824. foreach my $p (keys %pagesources) {
  1825. my $r=$sub->($p, location => $page);
  1826. my $i=$r->influences;
  1827. my $static=$r->influences_static;
  1828. foreach my $k (keys %$i) {
  1829. next unless $r || $static || $k eq $page;
  1830. $depends_simple{$page}{lc $k} |= $i->{$k};
  1831. }
  1832. last if $static;
  1833. }
  1834. $depends{$page}{$pagespec} |= $deptype;
  1835. return 1;
  1836. }
  1837. sub deptype (@) {
  1838. my $deptype=0;
  1839. foreach my $type (@_) {
  1840. if ($type eq 'presence') {
  1841. $deptype |= $DEPEND_PRESENCE;
  1842. }
  1843. elsif ($type eq 'links') {
  1844. $deptype |= $DEPEND_LINKS;
  1845. }
  1846. elsif ($type eq 'content') {
  1847. $deptype |= $DEPEND_CONTENT;
  1848. }
  1849. }
  1850. return $deptype;
  1851. }
  1852. my $file_prune_regexp;
  1853. sub file_pruned ($) {
  1854. my $file=shift;
  1855. if (defined $config{include} && length $config{include}) {
  1856. return 0 if $file =~ m/$config{include}/;
  1857. }
  1858. if (! defined $file_prune_regexp) {
  1859. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1860. $file_prune_regexp=qr/$file_prune_regexp/;
  1861. }
  1862. return $file =~ m/$file_prune_regexp/;
  1863. }
  1864. sub define_gettext () {
  1865. # If translation is needed, redefine the gettext function to do it.
  1866. # Otherwise, it becomes a quick no-op.
  1867. my $gettext_obj;
  1868. my $getobj;
  1869. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1870. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1871. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1872. $getobj=sub {
  1873. $gettext_obj=eval q{
  1874. use Locale::gettext q{textdomain};
  1875. Locale::gettext->domain('ikiwiki')
  1876. };
  1877. };
  1878. }
  1879. no warnings 'redefine';
  1880. *gettext=sub {
  1881. $getobj->() if $getobj;
  1882. if ($gettext_obj) {
  1883. $gettext_obj->get(shift);
  1884. }
  1885. else {
  1886. return shift;
  1887. }
  1888. };
  1889. *ngettext=sub {
  1890. $getobj->() if $getobj;
  1891. if ($gettext_obj) {
  1892. $gettext_obj->nget(@_);
  1893. }
  1894. else {
  1895. return ($_[2] == 1 ? $_[0] : $_[1])
  1896. }
  1897. };
  1898. }
  1899. sub gettext {
  1900. define_gettext();
  1901. gettext(@_);
  1902. }
  1903. sub ngettext {
  1904. define_gettext();
  1905. ngettext(@_);
  1906. }
  1907. sub yesno ($) {
  1908. my $val=shift;
  1909. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1910. }
  1911. sub inject {
  1912. # Injects a new function into the symbol table to replace an
  1913. # exported function.
  1914. my %params=@_;
  1915. # This is deep ugly perl foo, beware.
  1916. no strict;
  1917. no warnings;
  1918. if (! defined $params{parent}) {
  1919. $params{parent}='::';
  1920. $params{old}=\&{$params{name}};
  1921. $params{name}=~s/.*:://;
  1922. }
  1923. my $parent=$params{parent};
  1924. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1925. $ns = $params{parent} . $ns;
  1926. inject(%params, parent => $ns) unless $ns eq '::main::';
  1927. *{$ns . $params{name}} = $params{call}
  1928. if exists ${$ns}{$params{name}} &&
  1929. \&{${$ns}{$params{name}}} == $params{old};
  1930. }
  1931. use strict;
  1932. use warnings;
  1933. }
  1934. sub add_link ($$;$) {
  1935. my $page=shift;
  1936. my $link=shift;
  1937. my $type=shift;
  1938. push @{$links{$page}}, $link
  1939. unless grep { $_ eq $link } @{$links{$page}};
  1940. if (defined $type) {
  1941. $typedlinks{$page}{$type}{$link} = 1;
  1942. }
  1943. }
  1944. sub add_autofile ($$$) {
  1945. my $file=shift;
  1946. my $plugin=shift;
  1947. my $generator=shift;
  1948. $autofiles{$file}{plugin}=$plugin;
  1949. $autofiles{$file}{generator}=$generator;
  1950. }
  1951. sub sortspec_translate ($$) {
  1952. my $spec = shift;
  1953. my $reverse = shift;
  1954. my $code = "";
  1955. my @data;
  1956. while ($spec =~ m{
  1957. \s*
  1958. (-?) # group 1: perhaps negated
  1959. \s*
  1960. ( # group 2: a word
  1961. \w+\([^\)]*\) # command(params)
  1962. |
  1963. [^\s]+ # or anything else
  1964. )
  1965. \s*
  1966. }gx) {
  1967. my $negated = $1;
  1968. my $word = $2;
  1969. my $params = undef;
  1970. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1971. # command with parameters
  1972. $params = $2;
  1973. $word = $1;
  1974. }
  1975. elsif ($word !~ m/^\w+$/) {
  1976. error(sprintf(gettext("invalid sort type %s"), $word));
  1977. }
  1978. if (length $code) {
  1979. $code .= " || ";
  1980. }
  1981. if ($negated) {
  1982. $code .= "-";
  1983. }
  1984. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1985. if (defined $params) {
  1986. push @data, $params;
  1987. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1988. }
  1989. else {
  1990. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1991. }
  1992. }
  1993. else {
  1994. error(sprintf(gettext("unknown sort type %s"), $word));
  1995. }
  1996. }
  1997. if (! length $code) {
  1998. # undefined sorting method... sort arbitrarily
  1999. return sub { 0 };
  2000. }
  2001. if ($reverse) {
  2002. $code="-($code)";
  2003. }
  2004. no warnings;
  2005. return eval 'sub { '.$code.' }';
  2006. }
  2007. sub pagespec_translate ($) {
  2008. my $spec=shift;
  2009. # Convert spec to perl code.
  2010. my $code="";
  2011. my @data;
  2012. while ($spec=~m{
  2013. \s* # ignore whitespace
  2014. ( # 1: match a single word
  2015. \! # !
  2016. |
  2017. \( # (
  2018. |
  2019. \) # )
  2020. |
  2021. \w+\([^\)]*\) # command(params)
  2022. |
  2023. [^\s()]+ # any other text
  2024. )
  2025. \s* # ignore whitespace
  2026. }gx) {
  2027. my $word=$1;
  2028. if (lc $word eq 'and') {
  2029. $code.=' &';
  2030. }
  2031. elsif (lc $word eq 'or') {
  2032. $code.=' |';
  2033. }
  2034. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  2035. $code.=' '.$word;
  2036. }
  2037. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  2038. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  2039. push @data, $2;
  2040. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  2041. }
  2042. else {
  2043. push @data, qq{unknown function in pagespec "$word"};
  2044. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  2045. }
  2046. }
  2047. else {
  2048. push @data, $word;
  2049. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  2050. }
  2051. }
  2052. if (! length $code) {
  2053. $code="IkiWiki::FailReason->new('empty pagespec')";
  2054. }
  2055. no warnings;
  2056. return eval 'sub { my $page=shift; '.$code.' }';
  2057. }
  2058. sub pagespec_match ($$;@) {
  2059. my $page=shift;
  2060. my $spec=shift;
  2061. my @params=@_;
  2062. # Backwards compatability with old calling convention.
  2063. if (@params == 1) {
  2064. unshift @params, 'location';
  2065. }
  2066. my $sub=pagespec_translate($spec);
  2067. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  2068. if ! defined $sub;
  2069. return $sub->($page, @params);
  2070. }
  2071. sub pagespec_match_list ($$;@) {
  2072. my $page=shift;
  2073. my $pagespec=shift;
  2074. my %params=@_;
  2075. # Backwards compatability with old calling convention.
  2076. if (ref $page) {
  2077. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  2078. $params{list}=$page;
  2079. $page=$params{location}; # ugh!
  2080. }
  2081. my $sub=pagespec_translate($pagespec);
  2082. error "syntax error in pagespec \"$pagespec\""
  2083. if ! defined $sub;
  2084. my $sort=sortspec_translate($params{sort}, $params{reverse})
  2085. if defined $params{sort};
  2086. my @candidates;
  2087. if (exists $params{list}) {
  2088. @candidates=exists $params{filter}
  2089. ? grep { ! $params{filter}->($_) } @{$params{list}}
  2090. : @{$params{list}};
  2091. }
  2092. else {
  2093. @candidates=exists $params{filter}
  2094. ? grep { ! $params{filter}->($_) } keys %pagesources
  2095. : keys %pagesources;
  2096. }
  2097. # clear params, remainder is passed to pagespec
  2098. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  2099. my $num=$params{num};
  2100. delete @params{qw{num deptype reverse sort filter list}};
  2101. # when only the top matches will be returned, it's efficient to
  2102. # sort before matching to pagespec,
  2103. if (defined $num && defined $sort) {
  2104. @candidates=IkiWiki::SortSpec::sort_pages(
  2105. $sort, @candidates);
  2106. }
  2107. my @matches;
  2108. my $firstfail;
  2109. my $count=0;
  2110. my $accum=IkiWiki::SuccessReason->new();
  2111. foreach my $p (@candidates) {
  2112. my $r=$sub->($p, %params, location => $page);
  2113. error(sprintf(gettext("cannot match pages: %s"), $r))
  2114. if $r->isa("IkiWiki::ErrorReason");
  2115. unless ($r || $r->influences_static) {
  2116. $r->remove_influence($p);
  2117. }
  2118. $accum |= $r;
  2119. if ($r) {
  2120. push @matches, $p;
  2121. last if defined $num && ++$count == $num;
  2122. }
  2123. }
  2124. # Add simple dependencies for accumulated influences.
  2125. my $i=$accum->influences;
  2126. foreach my $k (keys %$i) {
  2127. $depends_simple{$page}{lc $k} |= $i->{$k};
  2128. }
  2129. # when all matches will be returned, it's efficient to
  2130. # sort after matching
  2131. if (! defined $num && defined $sort) {
  2132. return IkiWiki::SortSpec::sort_pages(
  2133. $sort, @matches);
  2134. }
  2135. else {
  2136. return @matches;
  2137. }
  2138. }
  2139. sub pagespec_valid ($) {
  2140. my $spec=shift;
  2141. return defined pagespec_translate($spec);
  2142. }
  2143. sub glob2re ($) {
  2144. my $re=quotemeta(shift);
  2145. $re=~s/\\\*/.*/g;
  2146. $re=~s/\\\?/./g;
  2147. return qr/^$re$/i;
  2148. }
  2149. package IkiWiki::FailReason;
  2150. use overload (
  2151. '""' => sub { $_[0][0] },
  2152. '0+' => sub { 0 },
  2153. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2154. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2155. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2156. fallback => 1,
  2157. );
  2158. our @ISA = 'IkiWiki::SuccessReason';
  2159. package IkiWiki::SuccessReason;
  2160. use overload (
  2161. '""' => sub { $_[0][0] },
  2162. '0+' => sub { 1 },
  2163. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2164. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2165. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2166. fallback => 1,
  2167. );
  2168. sub new {
  2169. my $class = shift;
  2170. my $value = shift;
  2171. return bless [$value, {@_}], $class;
  2172. }
  2173. sub influences {
  2174. my $this=shift;
  2175. $this->[1]={@_} if @_;
  2176. my %i=%{$this->[1]};
  2177. delete $i{""};
  2178. return \%i;
  2179. }
  2180. sub influences_static {
  2181. return ! $_[0][1]->{""};
  2182. }
  2183. sub merge_influences {
  2184. my $this=shift;
  2185. my $other=shift;
  2186. my $anded=shift;
  2187. if (! $anded || (($this || %{$this->[1]}) &&
  2188. ($other || %{$other->[1]}))) {
  2189. foreach my $influence (keys %{$other->[1]}) {
  2190. $this->[1]{$influence} |= $other->[1]{$influence};
  2191. }
  2192. }
  2193. else {
  2194. # influence blocker
  2195. $this->[1]={};
  2196. }
  2197. }
  2198. sub remove_influence {
  2199. my $this=shift;
  2200. my $torm=shift;
  2201. delete $this->[1]{$torm};
  2202. }
  2203. package IkiWiki::ErrorReason;
  2204. our @ISA = 'IkiWiki::FailReason';
  2205. package IkiWiki::PageSpec;
  2206. sub derel ($$) {
  2207. my $path=shift;
  2208. my $from=shift;
  2209. if ($path =~ m!^\.(/|$)!) {
  2210. if ($1) {
  2211. $from=~s#/?[^/]+$## if defined $from;
  2212. $path=~s#^\./##;
  2213. $path="$from/$path" if defined $from && length $from;
  2214. }
  2215. else {
  2216. $path = $from;
  2217. $path = "" unless defined $path;
  2218. }
  2219. }
  2220. return $path;
  2221. }
  2222. my %glob_cache;
  2223. sub match_glob ($$;@) {
  2224. my $page=shift;
  2225. my $glob=shift;
  2226. my %params=@_;
  2227. $glob=derel($glob, $params{location});
  2228. # Instead of converting the glob to a regex every time,
  2229. # cache the compiled regex to save time.
  2230. my $re=$glob_cache{$glob};
  2231. unless (defined $re) {
  2232. $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
  2233. }
  2234. if ($page =~ $re) {
  2235. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2236. return IkiWiki::SuccessReason->new("$glob matches $page");
  2237. }
  2238. else {
  2239. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2240. }
  2241. }
  2242. else {
  2243. return IkiWiki::FailReason->new("$glob does not match $page");
  2244. }
  2245. }
  2246. sub match_internal ($$;@) {
  2247. return match_glob(shift, shift, @_, internal => 1)
  2248. }
  2249. sub match_page ($$;@) {
  2250. my $page=shift;
  2251. my $match=match_glob($page, shift, @_);
  2252. if ($match) {
  2253. my $source=exists $IkiWiki::pagesources{$page} ?
  2254. $IkiWiki::pagesources{$page} :
  2255. $IkiWiki::delpagesources{$page};
  2256. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  2257. if (! defined $type) {
  2258. return IkiWiki::FailReason->new("$page is not a page");
  2259. }
  2260. }
  2261. return $match;
  2262. }
  2263. sub match_link ($$;@) {
  2264. my $page=shift;
  2265. my $link=lc(shift);
  2266. my %params=@_;
  2267. $link=derel($link, $params{location});
  2268. my $from=exists $params{location} ? $params{location} : '';
  2269. my $linktype=$params{linktype};
  2270. my $qualifier='';
  2271. if (defined $linktype) {
  2272. $qualifier=" with type $linktype";
  2273. }
  2274. my $links = $IkiWiki::links{$page};
  2275. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2276. unless $links && @{$links};
  2277. my $bestlink = IkiWiki::bestlink($from, $link);
  2278. foreach my $p (@{$links}) {
  2279. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2280. if (length $bestlink) {
  2281. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2282. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2283. }
  2284. }
  2285. else {
  2286. if (match_glob($p, $link, %params)) {
  2287. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2288. }
  2289. my ($p_rel)=$p=~/^\/?(.*)/;
  2290. $link=~s/^\///;
  2291. if (match_glob($p_rel, $link, %params)) {
  2292. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2293. }
  2294. }
  2295. }
  2296. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2297. }
  2298. sub match_backlink ($$;@) {
  2299. my $ret=match_link($_[1], $_[0], @_);
  2300. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2301. return $ret;
  2302. }
  2303. sub match_created_before ($$;@) {
  2304. my $page=shift;
  2305. my $testpage=shift;
  2306. my %params=@_;
  2307. $testpage=derel($testpage, $params{location});
  2308. if (exists $IkiWiki::pagectime{$testpage}) {
  2309. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2310. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2311. }
  2312. else {
  2313. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2314. }
  2315. }
  2316. else {
  2317. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2318. }
  2319. }
  2320. sub match_created_after ($$;@) {
  2321. my $page=shift;
  2322. my $testpage=shift;
  2323. my %params=@_;
  2324. $testpage=derel($testpage, $params{location});
  2325. if (exists $IkiWiki::pagectime{$testpage}) {
  2326. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2327. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2328. }
  2329. else {
  2330. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2331. }
  2332. }
  2333. else {
  2334. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2335. }
  2336. }
  2337. sub match_creation_day ($$;@) {
  2338. my $page=shift;
  2339. my $d=shift;
  2340. if ($d !~ /^\d+$/) {
  2341. return IkiWiki::ErrorReason->new("invalid day $d");
  2342. }
  2343. if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
  2344. return IkiWiki::SuccessReason->new('creation_day matched');
  2345. }
  2346. else {
  2347. return IkiWiki::FailReason->new('creation_day did not match');
  2348. }
  2349. }
  2350. sub match_creation_month ($$;@) {
  2351. my $page=shift;
  2352. my $m=shift;
  2353. if ($m !~ /^\d+$/) {
  2354. return IkiWiki::ErrorReason->new("invalid month $m");
  2355. }
  2356. if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
  2357. return IkiWiki::SuccessReason->new('creation_month matched');
  2358. }
  2359. else {
  2360. return IkiWiki::FailReason->new('creation_month did not match');
  2361. }
  2362. }
  2363. sub match_creation_year ($$;@) {
  2364. my $page=shift;
  2365. my $y=shift;
  2366. if ($y !~ /^\d+$/) {
  2367. return IkiWiki::ErrorReason->new("invalid year $y");
  2368. }
  2369. if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
  2370. return IkiWiki::SuccessReason->new('creation_year matched');
  2371. }
  2372. else {
  2373. return IkiWiki::FailReason->new('creation_year did not match');
  2374. }
  2375. }
  2376. sub match_user ($$;@) {
  2377. shift;
  2378. my $user=shift;
  2379. my %params=@_;
  2380. my $regexp=IkiWiki::glob2re($user);
  2381. if (! exists $params{user}) {
  2382. return IkiWiki::ErrorReason->new("no user specified");
  2383. }
  2384. if (defined $params{user} && $params{user}=~$regexp) {
  2385. return IkiWiki::SuccessReason->new("user is $user");
  2386. }
  2387. elsif (! defined $params{user}) {
  2388. return IkiWiki::FailReason->new("not logged in");
  2389. }
  2390. else {
  2391. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2392. }
  2393. }
  2394. sub match_admin ($$;@) {
  2395. shift;
  2396. shift;
  2397. my %params=@_;
  2398. if (! exists $params{user}) {
  2399. return IkiWiki::ErrorReason->new("no user specified");
  2400. }
  2401. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2402. return IkiWiki::SuccessReason->new("user is an admin");
  2403. }
  2404. elsif (! defined $params{user}) {
  2405. return IkiWiki::FailReason->new("not logged in");
  2406. }
  2407. else {
  2408. return IkiWiki::FailReason->new("user is not an admin");
  2409. }
  2410. }
  2411. sub match_ip ($$;@) {
  2412. shift;
  2413. my $ip=shift;
  2414. my %params=@_;
  2415. if (! exists $params{ip}) {
  2416. return IkiWiki::ErrorReason->new("no IP specified");
  2417. }
  2418. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2419. return IkiWiki::SuccessReason->new("IP is $ip");
  2420. }
  2421. else {
  2422. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2423. }
  2424. }
  2425. package IkiWiki::SortSpec;
  2426. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2427. # are easily available in this namespace, for cmp functions to use them.
  2428. sub sort_pages {
  2429. my $f=shift;
  2430. sort $f @_
  2431. }
  2432. sub cmp_title {
  2433. IkiWiki::pagetitle(IkiWiki::basename($a))
  2434. cmp
  2435. IkiWiki::pagetitle(IkiWiki::basename($b))
  2436. }
  2437. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2438. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2439. 1