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