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