summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 4084d499727127bad14a7f4bf9906797f8e0a4d3 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki;
  3. use warnings;
  4. use strict;
  5. use Encode;
  6. use HTML::Entities;
  7. use URI::Escape q{uri_escape_utf8};
  8. use POSIX ();
  9. use Storable;
  10. use open qw{:utf8 :std};
  11. use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
  12. %pagestate %wikistate %renderedfiles %oldrenderedfiles
  13. %pagesources %destsources %depends %depends_simple %hooks
  14. %forcerebuild %loaded_plugins %typedlinks %oldtypedlinks};
  15. use Exporter q{import};
  16. our @EXPORT = qw(hook debug error template htmlpage deptype
  17. 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
  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 => "location of template files",
  148. advanced => 1,
  149. safe => 0, # path
  150. rebuild => 1,
  151. },
  152. templatedirs => {
  153. type => "internal",
  154. default => [],
  155. description => "additional directories containing template files",
  156. safe => 0,
  157. rebuild => 0,
  158. },
  159. underlaydir => {
  160. type => "string",
  161. default => "$installdir/share/ikiwiki/basewiki",
  162. description => "base wiki source location",
  163. advanced => 1,
  164. safe => 0, # path
  165. rebuild => 0,
  166. },
  167. underlaydirbase => {
  168. type => "internal",
  169. default => "$installdir/share/ikiwiki",
  170. description => "parent directory containing additional underlays",
  171. safe => 0,
  172. rebuild => 0,
  173. },
  174. wrappers => {
  175. type => "internal",
  176. default => [],
  177. description => "wrappers to generate",
  178. safe => 0,
  179. rebuild => 0,
  180. },
  181. underlaydirs => {
  182. type => "internal",
  183. default => [],
  184. description => "additional underlays to use",
  185. safe => 0,
  186. rebuild => 0,
  187. },
  188. verbose => {
  189. type => "boolean",
  190. example => 1,
  191. description => "display verbose messages?",
  192. safe => 1,
  193. rebuild => 0,
  194. },
  195. syslog => {
  196. type => "boolean",
  197. example => 1,
  198. description => "log to syslog?",
  199. safe => 1,
  200. rebuild => 0,
  201. },
  202. usedirs => {
  203. type => "boolean",
  204. default => 1,
  205. description => "create output files named page/index.html?",
  206. safe => 0, # changing requires manual transition
  207. rebuild => 1,
  208. },
  209. prefix_directives => {
  210. type => "boolean",
  211. default => 1,
  212. description => "use '!'-prefixed preprocessor directives?",
  213. safe => 0, # changing requires manual transition
  214. rebuild => 1,
  215. },
  216. indexpages => {
  217. type => "boolean",
  218. default => 0,
  219. description => "use page/index.mdwn source files",
  220. safe => 1,
  221. rebuild => 1,
  222. },
  223. discussion => {
  224. type => "boolean",
  225. default => 1,
  226. description => "enable Discussion pages?",
  227. safe => 1,
  228. rebuild => 1,
  229. },
  230. discussionpage => {
  231. type => "string",
  232. default => gettext("Discussion"),
  233. description => "name of Discussion pages",
  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. if (! $config{rebuild}) {
  1378. $pagesources{$page}=$src;
  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 $template=shift;
  1485. foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
  1486. "$installdir/share/ikiwiki/templates") {
  1487. return "$dir/$template" if -e "$dir/$template";
  1488. }
  1489. return;
  1490. }
  1491. sub template_params (@) {
  1492. my $filename=template_file(shift);
  1493. if (! defined $filename) {
  1494. return if wantarray;
  1495. return "";
  1496. }
  1497. my @ret=(
  1498. filter => sub {
  1499. my $text_ref = shift;
  1500. ${$text_ref} = decode_utf8(${$text_ref});
  1501. },
  1502. filename => $filename,
  1503. loop_context_vars => 1,
  1504. die_on_bad_params => 0,
  1505. @_
  1506. );
  1507. return wantarray ? @ret : {@ret};
  1508. }
  1509. sub template ($;@) {
  1510. require HTML::Template;
  1511. return HTML::Template->new(template_params(@_));
  1512. }
  1513. sub misctemplate ($$;@) {
  1514. my $title=shift;
  1515. my $pagebody=shift;
  1516. my $template=template("misc.tmpl");
  1517. $template->param(
  1518. title => $title,
  1519. indexlink => indexlink(),
  1520. wikiname => $config{wikiname},
  1521. pagebody => $pagebody,
  1522. baseurl => baseurl(),
  1523. @_,
  1524. );
  1525. run_hooks(pagetemplate => sub {
  1526. shift->(page => "", destpage => "", template => $template);
  1527. });
  1528. return $template->output;
  1529. }
  1530. sub hook (@) {
  1531. my %param=@_;
  1532. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1533. error 'hook requires type, call, and id parameters';
  1534. }
  1535. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1536. $hooks{$param{type}}{$param{id}}=\%param;
  1537. return 1;
  1538. }
  1539. sub run_hooks ($$) {
  1540. # Calls the given sub for each hook of the given type,
  1541. # passing it the hook function to call.
  1542. my $type=shift;
  1543. my $sub=shift;
  1544. if (exists $hooks{$type}) {
  1545. my (@first, @middle, @last);
  1546. foreach my $id (keys %{$hooks{$type}}) {
  1547. if ($hooks{$type}{$id}{first}) {
  1548. push @first, $id;
  1549. }
  1550. elsif ($hooks{$type}{$id}{last}) {
  1551. push @last, $id;
  1552. }
  1553. else {
  1554. push @middle, $id;
  1555. }
  1556. }
  1557. foreach my $id (@first, @middle, @last) {
  1558. $sub->($hooks{$type}{$id}{call});
  1559. }
  1560. }
  1561. return 1;
  1562. }
  1563. sub rcs_update () {
  1564. $hooks{rcs}{rcs_update}{call}->(@_);
  1565. }
  1566. sub rcs_prepedit ($) {
  1567. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1568. }
  1569. sub rcs_commit ($$$;$$) {
  1570. $hooks{rcs}{rcs_commit}{call}->(@_);
  1571. }
  1572. sub rcs_commit_staged ($$$) {
  1573. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1574. }
  1575. sub rcs_add ($) {
  1576. $hooks{rcs}{rcs_add}{call}->(@_);
  1577. }
  1578. sub rcs_remove ($) {
  1579. $hooks{rcs}{rcs_remove}{call}->(@_);
  1580. }
  1581. sub rcs_rename ($$) {
  1582. $hooks{rcs}{rcs_rename}{call}->(@_);
  1583. }
  1584. sub rcs_recentchanges ($) {
  1585. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1586. }
  1587. sub rcs_diff ($) {
  1588. $hooks{rcs}{rcs_diff}{call}->(@_);
  1589. }
  1590. sub rcs_getctime ($) {
  1591. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1592. }
  1593. sub rcs_getmtime ($) {
  1594. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1595. }
  1596. sub rcs_receive () {
  1597. $hooks{rcs}{rcs_receive}{call}->();
  1598. }
  1599. sub add_depends ($$;$) {
  1600. my $page=shift;
  1601. my $pagespec=shift;
  1602. my $deptype=shift || $DEPEND_CONTENT;
  1603. # Is the pagespec a simple page name?
  1604. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1605. $pagespec !~ /[\s*?()!]/) {
  1606. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1607. return 1;
  1608. }
  1609. # Add explicit dependencies for influences.
  1610. my $sub=pagespec_translate($pagespec);
  1611. return unless defined $sub;
  1612. foreach my $p (keys %pagesources) {
  1613. my $r=$sub->($p, location => $page);
  1614. my $i=$r->influences;
  1615. foreach my $k (keys %$i) {
  1616. $depends_simple{$page}{lc $k} |= $i->{$k};
  1617. }
  1618. last if $r->influences_static;
  1619. }
  1620. $depends{$page}{$pagespec} |= $deptype;
  1621. return 1;
  1622. }
  1623. sub deptype (@) {
  1624. my $deptype=0;
  1625. foreach my $type (@_) {
  1626. if ($type eq 'presence') {
  1627. $deptype |= $DEPEND_PRESENCE;
  1628. }
  1629. elsif ($type eq 'links') {
  1630. $deptype |= $DEPEND_LINKS;
  1631. }
  1632. elsif ($type eq 'content') {
  1633. $deptype |= $DEPEND_CONTENT;
  1634. }
  1635. }
  1636. return $deptype;
  1637. }
  1638. my $file_prune_regexp;
  1639. sub file_pruned ($) {
  1640. my $file=shift;
  1641. if (defined $config{include} && length $config{include}) {
  1642. return 0 if $file =~ m/$config{include}/;
  1643. }
  1644. if (! defined $file_prune_regexp) {
  1645. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1646. $file_prune_regexp=qr/$file_prune_regexp/;
  1647. }
  1648. return $file =~ m/$file_prune_regexp/;
  1649. }
  1650. sub define_gettext () {
  1651. # If translation is needed, redefine the gettext function to do it.
  1652. # Otherwise, it becomes a quick no-op.
  1653. my $gettext_obj;
  1654. my $getobj;
  1655. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1656. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1657. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1658. $getobj=sub {
  1659. $gettext_obj=eval q{
  1660. use Locale::gettext q{textdomain};
  1661. Locale::gettext->domain('ikiwiki')
  1662. };
  1663. };
  1664. }
  1665. no warnings 'redefine';
  1666. *gettext=sub {
  1667. $getobj->() if $getobj;
  1668. if ($gettext_obj) {
  1669. $gettext_obj->get(shift);
  1670. }
  1671. else {
  1672. return shift;
  1673. }
  1674. };
  1675. *ngettext=sub {
  1676. $getobj->() if $getobj;
  1677. if ($gettext_obj) {
  1678. $gettext_obj->nget(@_);
  1679. }
  1680. else {
  1681. return ($_[2] == 1 ? $_[0] : $_[1])
  1682. }
  1683. };
  1684. }
  1685. sub gettext {
  1686. define_gettext();
  1687. gettext(@_);
  1688. }
  1689. sub ngettext {
  1690. define_gettext();
  1691. ngettext(@_);
  1692. }
  1693. sub yesno ($) {
  1694. my $val=shift;
  1695. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1696. }
  1697. sub inject {
  1698. # Injects a new function into the symbol table to replace an
  1699. # exported function.
  1700. my %params=@_;
  1701. # This is deep ugly perl foo, beware.
  1702. no strict;
  1703. no warnings;
  1704. if (! defined $params{parent}) {
  1705. $params{parent}='::';
  1706. $params{old}=\&{$params{name}};
  1707. $params{name}=~s/.*:://;
  1708. }
  1709. my $parent=$params{parent};
  1710. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1711. $ns = $params{parent} . $ns;
  1712. inject(%params, parent => $ns) unless $ns eq '::main::';
  1713. *{$ns . $params{name}} = $params{call}
  1714. if exists ${$ns}{$params{name}} &&
  1715. \&{${$ns}{$params{name}}} == $params{old};
  1716. }
  1717. use strict;
  1718. use warnings;
  1719. }
  1720. sub add_link ($$;$) {
  1721. my $page=shift;
  1722. my $link=shift;
  1723. my $type=shift;
  1724. push @{$links{$page}}, $link
  1725. unless grep { $_ eq $link } @{$links{$page}};
  1726. if (defined $type) {
  1727. $typedlinks{$page}{$type}{$link} = 1;
  1728. }
  1729. }
  1730. sub sortspec_translate ($$) {
  1731. my $spec = shift;
  1732. my $reverse = shift;
  1733. my $code = "";
  1734. my @data;
  1735. while ($spec =~ m{
  1736. \s*
  1737. (-?) # group 1: perhaps negated
  1738. \s*
  1739. ( # group 2: a word
  1740. \w+\([^\)]*\) # command(params)
  1741. |
  1742. [^\s]+ # or anything else
  1743. )
  1744. \s*
  1745. }gx) {
  1746. my $negated = $1;
  1747. my $word = $2;
  1748. my $params = undef;
  1749. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1750. # command with parameters
  1751. $params = $2;
  1752. $word = $1;
  1753. }
  1754. elsif ($word !~ m/^\w+$/) {
  1755. error(sprintf(gettext("invalid sort type %s"), $word));
  1756. }
  1757. if (length $code) {
  1758. $code .= " || ";
  1759. }
  1760. if ($negated) {
  1761. $code .= "-";
  1762. }
  1763. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1764. if (defined $params) {
  1765. push @data, $params;
  1766. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1767. }
  1768. else {
  1769. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1770. }
  1771. }
  1772. else {
  1773. error(sprintf(gettext("unknown sort type %s"), $word));
  1774. }
  1775. }
  1776. if (! length $code) {
  1777. # undefined sorting method... sort arbitrarily
  1778. return sub { 0 };
  1779. }
  1780. if ($reverse) {
  1781. $code="-($code)";
  1782. }
  1783. no warnings;
  1784. return eval 'sub { '.$code.' }';
  1785. }
  1786. sub pagespec_translate ($) {
  1787. my $spec=shift;
  1788. # Convert spec to perl code.
  1789. my $code="";
  1790. my @data;
  1791. while ($spec=~m{
  1792. \s* # ignore whitespace
  1793. ( # 1: match a single word
  1794. \! # !
  1795. |
  1796. \( # (
  1797. |
  1798. \) # )
  1799. |
  1800. \w+\([^\)]*\) # command(params)
  1801. |
  1802. [^\s()]+ # any other text
  1803. )
  1804. \s* # ignore whitespace
  1805. }gx) {
  1806. my $word=$1;
  1807. if (lc $word eq 'and') {
  1808. $code.=' &';
  1809. }
  1810. elsif (lc $word eq 'or') {
  1811. $code.=' |';
  1812. }
  1813. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1814. $code.=' '.$word;
  1815. }
  1816. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1817. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1818. push @data, $2;
  1819. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1820. }
  1821. else {
  1822. push @data, qq{unknown function in pagespec "$word"};
  1823. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1824. }
  1825. }
  1826. else {
  1827. push @data, $word;
  1828. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1829. }
  1830. }
  1831. if (! length $code) {
  1832. $code="IkiWiki::FailReason->new('empty pagespec')";
  1833. }
  1834. no warnings;
  1835. return eval 'sub { my $page=shift; '.$code.' }';
  1836. }
  1837. sub pagespec_match ($$;@) {
  1838. my $page=shift;
  1839. my $spec=shift;
  1840. my @params=@_;
  1841. # Backwards compatability with old calling convention.
  1842. if (@params == 1) {
  1843. unshift @params, 'location';
  1844. }
  1845. my $sub=pagespec_translate($spec);
  1846. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1847. if ! defined $sub;
  1848. return $sub->($page, @params);
  1849. }
  1850. sub pagespec_match_list ($$;@) {
  1851. my $page=shift;
  1852. my $pagespec=shift;
  1853. my %params=@_;
  1854. # Backwards compatability with old calling convention.
  1855. if (ref $page) {
  1856. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1857. $params{list}=$page;
  1858. $page=$params{location}; # ugh!
  1859. }
  1860. my $sub=pagespec_translate($pagespec);
  1861. error "syntax error in pagespec \"$pagespec\""
  1862. if ! defined $sub;
  1863. my $sort=sortspec_translate($params{sort}, $params{reverse})
  1864. if defined $params{sort};
  1865. my @candidates;
  1866. if (exists $params{list}) {
  1867. @candidates=exists $params{filter}
  1868. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1869. : @{$params{list}};
  1870. }
  1871. else {
  1872. @candidates=exists $params{filter}
  1873. ? grep { ! $params{filter}->($_) } keys %pagesources
  1874. : keys %pagesources;
  1875. }
  1876. # clear params, remainder is passed to pagespec
  1877. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1878. my $num=$params{num};
  1879. delete @params{qw{num deptype reverse sort filter list}};
  1880. # when only the top matches will be returned, it's efficient to
  1881. # sort before matching to pagespec,
  1882. if (defined $num && defined $sort) {
  1883. @candidates=IkiWiki::SortSpec::sort_pages(
  1884. $sort, @candidates);
  1885. }
  1886. my @matches;
  1887. my $firstfail;
  1888. my $count=0;
  1889. my $accum=IkiWiki::SuccessReason->new();
  1890. foreach my $p (@candidates) {
  1891. my $r=$sub->($p, %params, location => $page);
  1892. error(sprintf(gettext("cannot match pages: %s"), $r))
  1893. if $r->isa("IkiWiki::ErrorReason");
  1894. $accum |= $r;
  1895. if ($r) {
  1896. push @matches, $p;
  1897. last if defined $num && ++$count == $num;
  1898. }
  1899. }
  1900. # Add simple dependencies for accumulated influences.
  1901. my $i=$accum->influences;
  1902. foreach my $k (keys %$i) {
  1903. $depends_simple{$page}{lc $k} |= $i->{$k};
  1904. }
  1905. # when all matches will be returned, it's efficient to
  1906. # sort after matching
  1907. if (! defined $num && defined $sort) {
  1908. return IkiWiki::SortSpec::sort_pages(
  1909. $sort, @matches);
  1910. }
  1911. else {
  1912. return @matches;
  1913. }
  1914. }
  1915. sub pagespec_valid ($) {
  1916. my $spec=shift;
  1917. return defined pagespec_translate($spec);
  1918. }
  1919. sub glob2re ($) {
  1920. my $re=quotemeta(shift);
  1921. $re=~s/\\\*/.*/g;
  1922. $re=~s/\\\?/./g;
  1923. return $re;
  1924. }
  1925. package IkiWiki::FailReason;
  1926. use overload (
  1927. '""' => sub { $_[0][0] },
  1928. '0+' => sub { 0 },
  1929. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  1930. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  1931. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  1932. fallback => 1,
  1933. );
  1934. our @ISA = 'IkiWiki::SuccessReason';
  1935. package IkiWiki::SuccessReason;
  1936. use overload (
  1937. '""' => sub { $_[0][0] },
  1938. '0+' => sub { 1 },
  1939. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  1940. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  1941. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  1942. fallback => 1,
  1943. );
  1944. sub new {
  1945. my $class = shift;
  1946. my $value = shift;
  1947. return bless [$value, {@_}], $class;
  1948. }
  1949. sub influences {
  1950. my $this=shift;
  1951. $this->[1]={@_} if @_;
  1952. my %i=%{$this->[1]};
  1953. delete $i{""};
  1954. return \%i;
  1955. }
  1956. sub influences_static {
  1957. return ! $_[0][1]->{""};
  1958. }
  1959. sub merge_influences {
  1960. my $this=shift;
  1961. my $other=shift;
  1962. my $anded=shift;
  1963. if (! $anded || (($this || %{$this->[1]}) &&
  1964. ($other || %{$other->[1]}))) {
  1965. foreach my $influence (keys %{$other->[1]}) {
  1966. $this->[1]{$influence} |= $other->[1]{$influence};
  1967. }
  1968. }
  1969. else {
  1970. # influence blocker
  1971. $this->[1]={};
  1972. }
  1973. }
  1974. package IkiWiki::ErrorReason;
  1975. our @ISA = 'IkiWiki::FailReason';
  1976. package IkiWiki::PageSpec;
  1977. sub derel ($$) {
  1978. my $path=shift;
  1979. my $from=shift;
  1980. if ($path =~ m!^\./!) {
  1981. $from=~s#/?[^/]+$## if defined $from;
  1982. $path=~s#^\./##;
  1983. $path="$from/$path" if length $from;
  1984. }
  1985. return $path;
  1986. }
  1987. sub match_glob ($$;@) {
  1988. my $page=shift;
  1989. my $glob=shift;
  1990. my %params=@_;
  1991. $glob=derel($glob, $params{location});
  1992. my $regexp=IkiWiki::glob2re($glob);
  1993. if ($page=~/^$regexp$/i) {
  1994. if (! IkiWiki::isinternal($page) || $params{internal}) {
  1995. return IkiWiki::SuccessReason->new("$glob matches $page");
  1996. }
  1997. else {
  1998. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  1999. }
  2000. }
  2001. else {
  2002. return IkiWiki::FailReason->new("$glob does not match $page");
  2003. }
  2004. }
  2005. sub match_internal ($$;@) {
  2006. return match_glob($_[0], $_[1], @_, internal => 1)
  2007. }
  2008. sub match_link ($$;@) {
  2009. my $page=shift;
  2010. my $link=lc(shift);
  2011. my %params=@_;
  2012. $link=derel($link, $params{location});
  2013. my $from=exists $params{location} ? $params{location} : '';
  2014. my $linktype=$params{linktype};
  2015. my $qualifier='';
  2016. if (defined $linktype) {
  2017. $qualifier=" with type $linktype";
  2018. }
  2019. my $links = $IkiWiki::links{$page};
  2020. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2021. unless $links && @{$links};
  2022. my $bestlink = IkiWiki::bestlink($from, $link);
  2023. foreach my $p (@{$links}) {
  2024. if (length $bestlink) {
  2025. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
  2026. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2027. }
  2028. }
  2029. else {
  2030. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
  2031. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2032. }
  2033. my ($p_rel)=$p=~/^\/?(.*)/;
  2034. $link=~s/^\///;
  2035. if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
  2036. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2037. }
  2038. }
  2039. }
  2040. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2041. }
  2042. sub match_backlink ($$;@) {
  2043. my $ret=match_link($_[1], $_[0], @_);
  2044. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2045. return $ret;
  2046. }
  2047. sub match_created_before ($$;@) {
  2048. my $page=shift;
  2049. my $testpage=shift;
  2050. my %params=@_;
  2051. $testpage=derel($testpage, $params{location});
  2052. if (exists $IkiWiki::pagectime{$testpage}) {
  2053. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2054. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2055. }
  2056. else {
  2057. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2058. }
  2059. }
  2060. else {
  2061. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2062. }
  2063. }
  2064. sub match_created_after ($$;@) {
  2065. my $page=shift;
  2066. my $testpage=shift;
  2067. my %params=@_;
  2068. $testpage=derel($testpage, $params{location});
  2069. if (exists $IkiWiki::pagectime{$testpage}) {
  2070. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2071. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2072. }
  2073. else {
  2074. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2075. }
  2076. }
  2077. else {
  2078. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2079. }
  2080. }
  2081. sub match_creation_day ($$;@) {
  2082. if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2083. return IkiWiki::SuccessReason->new('creation_day matched');
  2084. }
  2085. else {
  2086. return IkiWiki::FailReason->new('creation_day did not match');
  2087. }
  2088. }
  2089. sub match_creation_month ($$;@) {
  2090. if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2091. return IkiWiki::SuccessReason->new('creation_month matched');
  2092. }
  2093. else {
  2094. return IkiWiki::FailReason->new('creation_month did not match');
  2095. }
  2096. }
  2097. sub match_creation_year ($$;@) {
  2098. if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2099. return IkiWiki::SuccessReason->new('creation_year matched');
  2100. }
  2101. else {
  2102. return IkiWiki::FailReason->new('creation_year did not match');
  2103. }
  2104. }
  2105. sub match_user ($$;@) {
  2106. shift;
  2107. my $user=shift;
  2108. my %params=@_;
  2109. my $regexp=IkiWiki::glob2re($user);
  2110. if (! exists $params{user}) {
  2111. return IkiWiki::ErrorReason->new("no user specified");
  2112. }
  2113. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2114. return IkiWiki::SuccessReason->new("user is $user");
  2115. }
  2116. elsif (! defined $params{user}) {
  2117. return IkiWiki::FailReason->new("not logged in");
  2118. }
  2119. else {
  2120. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2121. }
  2122. }
  2123. sub match_admin ($$;@) {
  2124. shift;
  2125. shift;
  2126. my %params=@_;
  2127. if (! exists $params{user}) {
  2128. return IkiWiki::ErrorReason->new("no user specified");
  2129. }
  2130. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2131. return IkiWiki::SuccessReason->new("user is an admin");
  2132. }
  2133. elsif (! defined $params{user}) {
  2134. return IkiWiki::FailReason->new("not logged in");
  2135. }
  2136. else {
  2137. return IkiWiki::FailReason->new("user is not an admin");
  2138. }
  2139. }
  2140. sub match_ip ($$;@) {
  2141. shift;
  2142. my $ip=shift;
  2143. my %params=@_;
  2144. if (! exists $params{ip}) {
  2145. return IkiWiki::ErrorReason->new("no IP specified");
  2146. }
  2147. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2148. return IkiWiki::SuccessReason->new("IP is $ip");
  2149. }
  2150. else {
  2151. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2152. }
  2153. }
  2154. package IkiWiki::SortSpec;
  2155. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2156. # are easily available in this namespace, for cmp functions to use them.
  2157. sub sort_pages {
  2158. my $f=shift;
  2159. sort $f @_
  2160. }
  2161. sub cmp_title {
  2162. IkiWiki::pagetitle(IkiWiki::basename($a))
  2163. cmp
  2164. IkiWiki::pagetitle(IkiWiki::basename($b))
  2165. }
  2166. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2167. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2168. 1