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