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