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