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