summaryrefslogtreecommitdiff
path: root/IkiWiki.pm
blob: 701f7137dd78483215637e205bbde0b720ea0387 (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 htmllink ($$$;@) {
  974. my $lpage=shift; # the page doing the linking
  975. my $page=shift; # the page that will contain the link (different for inline)
  976. my $link=shift;
  977. my %opts=@_;
  978. $link=~s/\/$//;
  979. my $bestlink;
  980. if (! $opts{forcesubpage}) {
  981. $bestlink=bestlink($lpage, $link);
  982. }
  983. else {
  984. $bestlink="$lpage/".lc($link);
  985. }
  986. my $linktext;
  987. if (defined $opts{linktext}) {
  988. $linktext=$opts{linktext};
  989. }
  990. else {
  991. $linktext=pagetitle(basename($link));
  992. }
  993. return "<span class=\"selflink\">$linktext</span>"
  994. if length $bestlink && $page eq $bestlink &&
  995. ! defined $opts{anchor};
  996. if (! $destsources{$bestlink}) {
  997. $bestlink=htmlpage($bestlink);
  998. if (! $destsources{$bestlink}) {
  999. my $cgilink = "";
  1000. if (length $config{cgiurl}) {
  1001. $cgilink = "<a href=\"".
  1002. cgiurl(
  1003. do => "create",
  1004. page => lc($link),
  1005. from => $lpage
  1006. )."\" rel=\"nofollow\">?</a>";
  1007. }
  1008. return "<span class=\"createlink\">$cgilink$linktext</span>"
  1009. }
  1010. }
  1011. $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
  1012. $bestlink=beautify_urlpath($bestlink);
  1013. if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
  1014. return "<img src=\"$bestlink\" alt=\"$linktext\" />";
  1015. }
  1016. if (defined $opts{anchor}) {
  1017. $bestlink.="#".$opts{anchor};
  1018. }
  1019. my @attrs;
  1020. foreach my $attr (qw{rel class title}) {
  1021. if (defined $opts{$attr}) {
  1022. push @attrs, " $attr=\"$opts{$attr}\"";
  1023. }
  1024. }
  1025. return "<a href=\"$bestlink\"@attrs>$linktext</a>";
  1026. }
  1027. sub userpage ($) {
  1028. my $user=shift;
  1029. return length $config{userdir} ? "$config{userdir}/$user" : $user;
  1030. }
  1031. sub openiduser ($) {
  1032. my $user=shift;
  1033. if ($user =~ m!^https?://! &&
  1034. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  1035. my $display;
  1036. if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
  1037. $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
  1038. }
  1039. else {
  1040. # backcompat with old version
  1041. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  1042. $display=$oid->display;
  1043. }
  1044. # Convert "user.somehost.com" to "user [somehost.com]"
  1045. # (also "user.somehost.co.uk")
  1046. if ($display !~ /\[/) {
  1047. $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
  1048. }
  1049. # Convert "http://somehost.com/user" to "user [somehost.com]".
  1050. # (also "https://somehost.com/user/")
  1051. if ($display !~ /\[/) {
  1052. $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
  1053. }
  1054. $display=~s!^https?://!!; # make sure this is removed
  1055. eval q{use CGI 'escapeHTML'};
  1056. error($@) if $@;
  1057. return escapeHTML($display);
  1058. }
  1059. return;
  1060. }
  1061. sub htmlize ($$$$) {
  1062. my $page=shift;
  1063. my $destpage=shift;
  1064. my $type=shift;
  1065. my $content=shift;
  1066. my $oneline = $content !~ /\n/;
  1067. if (exists $hooks{htmlize}{$type}) {
  1068. $content=$hooks{htmlize}{$type}{call}->(
  1069. page => $page,
  1070. content => $content,
  1071. );
  1072. }
  1073. else {
  1074. error("htmlization of $type not supported");
  1075. }
  1076. run_hooks(sanitize => sub {
  1077. $content=shift->(
  1078. page => $page,
  1079. destpage => $destpage,
  1080. content => $content,
  1081. );
  1082. });
  1083. if ($oneline) {
  1084. # hack to get rid of enclosing junk added by markdown
  1085. # and other htmlizers/sanitizers
  1086. $content=~s/^<p>//i;
  1087. $content=~s/<\/p>\n*$//i;
  1088. }
  1089. return $content;
  1090. }
  1091. sub linkify ($$$) {
  1092. my $page=shift;
  1093. my $destpage=shift;
  1094. my $content=shift;
  1095. run_hooks(linkify => sub {
  1096. $content=shift->(
  1097. page => $page,
  1098. destpage => $destpage,
  1099. content => $content,
  1100. );
  1101. });
  1102. return $content;
  1103. }
  1104. our %preprocessing;
  1105. our $preprocess_preview=0;
  1106. sub preprocess ($$$;$$) {
  1107. my $page=shift; # the page the data comes from
  1108. my $destpage=shift; # the page the data will appear in (different for inline)
  1109. my $content=shift;
  1110. my $scan=shift;
  1111. my $preview=shift;
  1112. # Using local because it needs to be set within any nested calls
  1113. # of this function.
  1114. local $preprocess_preview=$preview if defined $preview;
  1115. my $handle=sub {
  1116. my $escape=shift;
  1117. my $prefix=shift;
  1118. my $command=shift;
  1119. my $params=shift;
  1120. $params="" if ! defined $params;
  1121. if (length $escape) {
  1122. return "[[$prefix$command $params]]";
  1123. }
  1124. elsif (exists $hooks{preprocess}{$command}) {
  1125. return "" if $scan && ! $hooks{preprocess}{$command}{scan};
  1126. # Note: preserve order of params, some plugins may
  1127. # consider it significant.
  1128. my @params;
  1129. while ($params =~ m{
  1130. (?:([-\w]+)=)? # 1: named parameter key?
  1131. (?:
  1132. """(.*?)""" # 2: triple-quoted value
  1133. |
  1134. "([^"]*?)" # 3: single-quoted value
  1135. |
  1136. (\S+) # 4: unquoted value
  1137. )
  1138. (?:\s+|$) # delimiter to next param
  1139. }sgx) {
  1140. my $key=$1;
  1141. my $val;
  1142. if (defined $2) {
  1143. $val=$2;
  1144. $val=~s/\r\n/\n/mg;
  1145. $val=~s/^\n+//g;
  1146. $val=~s/\n+$//g;
  1147. }
  1148. elsif (defined $3) {
  1149. $val=$3;
  1150. }
  1151. elsif (defined $4) {
  1152. $val=$4;
  1153. }
  1154. if (defined $key) {
  1155. push @params, $key, $val;
  1156. }
  1157. else {
  1158. push @params, $val, '';
  1159. }
  1160. }
  1161. if ($preprocessing{$page}++ > 3) {
  1162. # Avoid loops of preprocessed pages preprocessing
  1163. # other pages that preprocess them, etc.
  1164. return "[[!$command <span class=\"error\">".
  1165. sprintf(gettext("preprocessing loop detected on %s at depth %i"),
  1166. $page, $preprocessing{$page}).
  1167. "</span>]]";
  1168. }
  1169. my $ret;
  1170. if (! $scan) {
  1171. $ret=eval {
  1172. $hooks{preprocess}{$command}{call}->(
  1173. @params,
  1174. page => $page,
  1175. destpage => $destpage,
  1176. preview => $preprocess_preview,
  1177. );
  1178. };
  1179. if ($@) {
  1180. my $error=$@;
  1181. chomp $error;
  1182. $ret="[[!$command <span class=\"error\">".
  1183. gettext("Error").": $error"."</span>]]";
  1184. }
  1185. }
  1186. else {
  1187. # use void context during scan pass
  1188. eval {
  1189. $hooks{preprocess}{$command}{call}->(
  1190. @params,
  1191. page => $page,
  1192. destpage => $destpage,
  1193. preview => $preprocess_preview,
  1194. );
  1195. };
  1196. $ret="";
  1197. }
  1198. $preprocessing{$page}--;
  1199. return $ret;
  1200. }
  1201. else {
  1202. return "[[$prefix$command $params]]";
  1203. }
  1204. };
  1205. my $regex;
  1206. if ($config{prefix_directives}) {
  1207. $regex = qr{
  1208. (\\?) # 1: escape?
  1209. \[\[(!) # directive open; 2: prefix
  1210. ([-\w]+) # 3: command
  1211. ( # 4: the parameters..
  1212. \s+ # Must have space if parameters present
  1213. (?:
  1214. (?:[-\w]+=)? # named parameter key?
  1215. (?:
  1216. """.*?""" # triple-quoted value
  1217. |
  1218. "[^"]*?" # single-quoted value
  1219. |
  1220. [^"\s\]]+ # unquoted value
  1221. )
  1222. \s* # whitespace or end
  1223. # of directive
  1224. )
  1225. *)? # 0 or more parameters
  1226. \]\] # directive closed
  1227. }sx;
  1228. }
  1229. else {
  1230. $regex = qr{
  1231. (\\?) # 1: escape?
  1232. \[\[(!?) # directive open; 2: optional prefix
  1233. ([-\w]+) # 3: command
  1234. \s+
  1235. ( # 4: the parameters..
  1236. (?:
  1237. (?:[-\w]+=)? # named parameter key?
  1238. (?:
  1239. """.*?""" # triple-quoted value
  1240. |
  1241. "[^"]*?" # single-quoted value
  1242. |
  1243. [^"\s\]]+ # unquoted value
  1244. )
  1245. \s* # whitespace or end
  1246. # of directive
  1247. )
  1248. *) # 0 or more parameters
  1249. \]\] # directive closed
  1250. }sx;
  1251. }
  1252. $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
  1253. return $content;
  1254. }
  1255. sub filter ($$$) {
  1256. my $page=shift;
  1257. my $destpage=shift;
  1258. my $content=shift;
  1259. run_hooks(filter => sub {
  1260. $content=shift->(page => $page, destpage => $destpage,
  1261. content => $content);
  1262. });
  1263. return $content;
  1264. }
  1265. sub check_canedit ($$$;$) {
  1266. my $page=shift;
  1267. my $q=shift;
  1268. my $session=shift;
  1269. my $nonfatal=shift;
  1270. my $canedit;
  1271. run_hooks(canedit => sub {
  1272. return if defined $canedit;
  1273. my $ret=shift->($page, $q, $session);
  1274. if (defined $ret) {
  1275. if ($ret eq "") {
  1276. $canedit=1;
  1277. }
  1278. elsif (ref $ret eq 'CODE') {
  1279. $ret->() unless $nonfatal;
  1280. $canedit=0;
  1281. }
  1282. elsif (defined $ret) {
  1283. error($ret) unless $nonfatal;
  1284. $canedit=0;
  1285. }
  1286. }
  1287. });
  1288. return defined $canedit ? $canedit : 1;
  1289. }
  1290. sub check_content (@) {
  1291. my %params=@_;
  1292. return 1 if ! exists $hooks{checkcontent}; # optimisation
  1293. if (exists $pagesources{$params{page}}) {
  1294. my @diff;
  1295. my %old=map { $_ => 1 }
  1296. split("\n", readfile(srcfile($pagesources{$params{page}})));
  1297. foreach my $line (split("\n", $params{content})) {
  1298. push @diff, $line if ! exists $old{$line};
  1299. }
  1300. $params{diff}=join("\n", @diff);
  1301. }
  1302. my $ok;
  1303. run_hooks(checkcontent => sub {
  1304. return if defined $ok;
  1305. my $ret=shift->(%params);
  1306. if (defined $ret) {
  1307. if ($ret eq "") {
  1308. $ok=1;
  1309. }
  1310. elsif (ref $ret eq 'CODE') {
  1311. $ret->() unless $params{nonfatal};
  1312. $ok=0;
  1313. }
  1314. elsif (defined $ret) {
  1315. error($ret) unless $params{nonfatal};
  1316. $ok=0;
  1317. }
  1318. }
  1319. });
  1320. return defined $ok ? $ok : 1;
  1321. }
  1322. my $wikilock;
  1323. sub lockwiki () {
  1324. # Take an exclusive lock on the wiki to prevent multiple concurrent
  1325. # run issues. The lock will be dropped on program exit.
  1326. if (! -d $config{wikistatedir}) {
  1327. mkdir($config{wikistatedir});
  1328. }
  1329. open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
  1330. error ("cannot write to $config{wikistatedir}/lockfile: $!");
  1331. if (! flock($wikilock, 2)) { # LOCK_EX
  1332. error("failed to get lock");
  1333. }
  1334. return 1;
  1335. }
  1336. sub unlockwiki () {
  1337. POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
  1338. return close($wikilock) if $wikilock;
  1339. return;
  1340. }
  1341. my $commitlock;
  1342. sub commit_hook_enabled () {
  1343. open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
  1344. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1345. if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
  1346. close($commitlock) || error("failed closing commitlock: $!");
  1347. return 0;
  1348. }
  1349. close($commitlock) || error("failed closing commitlock: $!");
  1350. return 1;
  1351. }
  1352. sub disable_commit_hook () {
  1353. open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
  1354. error("cannot write to $config{wikistatedir}/commitlock: $!");
  1355. if (! flock($commitlock, 2)) { # LOCK_EX
  1356. error("failed to get commit lock");
  1357. }
  1358. return 1;
  1359. }
  1360. sub enable_commit_hook () {
  1361. return close($commitlock) if $commitlock;
  1362. return;
  1363. }
  1364. sub loadindex () {
  1365. %oldrenderedfiles=%pagectime=();
  1366. if (! $config{rebuild}) {
  1367. %pagesources=%pagemtime=%oldlinks=%links=%depends=
  1368. %destsources=%renderedfiles=%pagecase=%pagestate=
  1369. %depends_simple=%typedlinks=%oldtypedlinks=();
  1370. }
  1371. my $in;
  1372. if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
  1373. if (-e "$config{wikistatedir}/index") {
  1374. system("ikiwiki-transition", "indexdb", $config{srcdir});
  1375. open ($in, "<", "$config{wikistatedir}/indexdb") || return;
  1376. }
  1377. else {
  1378. $config{gettime}=1; # first build
  1379. return;
  1380. }
  1381. }
  1382. my $index=Storable::fd_retrieve($in);
  1383. if (! defined $index) {
  1384. return 0;
  1385. }
  1386. my $pages;
  1387. if (exists $index->{version} && ! ref $index->{version}) {
  1388. $pages=$index->{page};
  1389. %wikistate=%{$index->{state}};
  1390. }
  1391. else {
  1392. $pages=$index;
  1393. %wikistate=();
  1394. }
  1395. foreach my $src (keys %$pages) {
  1396. my $d=$pages->{$src};
  1397. my $page=pagename($src);
  1398. $pagectime{$page}=$d->{ctime};
  1399. $pagesources{$page}=$src;
  1400. if (! $config{rebuild}) {
  1401. $pagemtime{$page}=$d->{mtime};
  1402. $renderedfiles{$page}=$d->{dest};
  1403. if (exists $d->{links} && ref $d->{links}) {
  1404. $links{$page}=$d->{links};
  1405. $oldlinks{$page}=[@{$d->{links}}];
  1406. }
  1407. if (ref $d->{depends_simple} eq 'ARRAY') {
  1408. # old format
  1409. $depends_simple{$page}={
  1410. map { $_ => 1 } @{$d->{depends_simple}}
  1411. };
  1412. }
  1413. elsif (exists $d->{depends_simple}) {
  1414. $depends_simple{$page}=$d->{depends_simple};
  1415. }
  1416. if (exists $d->{dependslist}) {
  1417. # old format
  1418. $depends{$page}={
  1419. map { $_ => $DEPEND_CONTENT }
  1420. @{$d->{dependslist}}
  1421. };
  1422. }
  1423. elsif (exists $d->{depends} && ! ref $d->{depends}) {
  1424. # old format
  1425. $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
  1426. }
  1427. elsif (exists $d->{depends}) {
  1428. $depends{$page}=$d->{depends};
  1429. }
  1430. if (exists $d->{state}) {
  1431. $pagestate{$page}=$d->{state};
  1432. }
  1433. if (exists $d->{typedlinks}) {
  1434. $typedlinks{$page}=$d->{typedlinks};
  1435. while (my ($type, $links) = each %{$typedlinks{$page}}) {
  1436. next unless %$links;
  1437. $oldtypedlinks{$page}{$type} = {%$links};
  1438. }
  1439. }
  1440. }
  1441. $oldrenderedfiles{$page}=[@{$d->{dest}}];
  1442. }
  1443. foreach my $page (keys %pagesources) {
  1444. $pagecase{lc $page}=$page;
  1445. }
  1446. foreach my $page (keys %renderedfiles) {
  1447. $destsources{$_}=$page foreach @{$renderedfiles{$page}};
  1448. }
  1449. return close($in);
  1450. }
  1451. sub saveindex () {
  1452. run_hooks(savestate => sub { shift->() });
  1453. my %hookids;
  1454. foreach my $type (keys %hooks) {
  1455. $hookids{$_}=1 foreach keys %{$hooks{$type}};
  1456. }
  1457. my @hookids=keys %hookids;
  1458. if (! -d $config{wikistatedir}) {
  1459. mkdir($config{wikistatedir});
  1460. }
  1461. my $newfile="$config{wikistatedir}/indexdb.new";
  1462. my $cleanup = sub { unlink($newfile) };
  1463. open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
  1464. my %index;
  1465. foreach my $page (keys %pagemtime) {
  1466. next unless $pagemtime{$page};
  1467. my $src=$pagesources{$page};
  1468. $index{page}{$src}={
  1469. ctime => $pagectime{$page},
  1470. mtime => $pagemtime{$page},
  1471. dest => $renderedfiles{$page},
  1472. links => $links{$page},
  1473. };
  1474. if (exists $depends{$page}) {
  1475. $index{page}{$src}{depends} = $depends{$page};
  1476. }
  1477. if (exists $depends_simple{$page}) {
  1478. $index{page}{$src}{depends_simple} = $depends_simple{$page};
  1479. }
  1480. if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
  1481. $index{page}{$src}{typedlinks} = $typedlinks{$page};
  1482. }
  1483. if (exists $pagestate{$page}) {
  1484. foreach my $id (@hookids) {
  1485. foreach my $key (keys %{$pagestate{$page}{$id}}) {
  1486. $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
  1487. }
  1488. }
  1489. }
  1490. }
  1491. $index{state}={};
  1492. foreach my $id (@hookids) {
  1493. foreach my $key (keys %{$wikistate{$id}}) {
  1494. $index{state}{$id}{$key}=$wikistate{$id}{$key};
  1495. }
  1496. }
  1497. $index{version}="3";
  1498. my $ret=Storable::nstore_fd(\%index, $out);
  1499. return if ! defined $ret || ! $ret;
  1500. close $out || error("failed saving to $newfile: $!", $cleanup);
  1501. rename($newfile, "$config{wikistatedir}/indexdb") ||
  1502. error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
  1503. return 1;
  1504. }
  1505. sub template_file ($) {
  1506. my $name=shift;
  1507. my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
  1508. if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
  1509. $tpage=$pagesources{$tpage};
  1510. $name.=".tmpl";
  1511. }
  1512. my $template=srcfile($tpage, 1);
  1513. if (defined $template) {
  1514. return $template, $tpage, 1 if wantarray;
  1515. return $template;
  1516. }
  1517. else {
  1518. $name=~s:/::; # avoid path traversal
  1519. foreach my $dir ($config{templatedir},
  1520. "$installdir/share/ikiwiki/templates") {
  1521. if (-e "$dir/$name") {
  1522. $template="$dir/$name";
  1523. last;
  1524. }
  1525. }
  1526. if (defined $template) {
  1527. return $template, $tpage if wantarray;
  1528. return $template;
  1529. }
  1530. }
  1531. return;
  1532. }
  1533. sub template_depends ($$;@) {
  1534. my $name=shift;
  1535. my $page=shift;
  1536. my ($filename, $tpage, $untrusted)=template_file($name);
  1537. if (defined $page && defined $tpage) {
  1538. add_depends($page, $tpage);
  1539. }
  1540. return unless defined $filename;
  1541. my @opts=(
  1542. filter => sub {
  1543. my $text_ref = shift;
  1544. ${$text_ref} = decode_utf8(${$text_ref});
  1545. },
  1546. loop_context_vars => 1,
  1547. die_on_bad_params => 0,
  1548. filename => $filename,
  1549. @_,
  1550. ($untrusted ? (no_includes => 1) : ()),
  1551. );
  1552. return @opts if wantarray;
  1553. require HTML::Template;
  1554. return HTML::Template->new(@opts);
  1555. }
  1556. sub template ($;@) {
  1557. template_depends(shift, undef, @_);
  1558. }
  1559. sub misctemplate ($$;@) {
  1560. my $title=shift;
  1561. my $content=shift;
  1562. my %params=@_;
  1563. my $template=template("page.tmpl");
  1564. my $page="";
  1565. if (exists $params{page}) {
  1566. $page=delete $params{page};
  1567. }
  1568. run_hooks(pagetemplate => sub {
  1569. shift->(
  1570. page => $page,
  1571. destpage => $page,
  1572. template => $template,
  1573. );
  1574. });
  1575. templateactions($template, "");
  1576. $template->param(
  1577. dynamic => 1,
  1578. title => $title,
  1579. wikiname => $config{wikiname},
  1580. content => $content,
  1581. baseurl => baseurl(),
  1582. html5 => $config{html5},
  1583. %params,
  1584. );
  1585. return $template->output;
  1586. }
  1587. sub templateactions ($$) {
  1588. my $template=shift;
  1589. my $page=shift;
  1590. my $have_actions=0;
  1591. my @actions;
  1592. run_hooks(pageactions => sub {
  1593. push @actions, map { { action => $_ } }
  1594. grep { defined } shift->(page => $page);
  1595. });
  1596. $template->param(actions => \@actions);
  1597. if ($config{cgiurl} && exists $hooks{auth}) {
  1598. $template->param(prefsurl => cgiurl(do => "prefs"));
  1599. $have_actions=1;
  1600. }
  1601. if ($have_actions || @actions) {
  1602. $template->param(have_actions => 1);
  1603. }
  1604. }
  1605. sub hook (@) {
  1606. my %param=@_;
  1607. if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
  1608. error 'hook requires type, call, and id parameters';
  1609. }
  1610. return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
  1611. $hooks{$param{type}}{$param{id}}=\%param;
  1612. return 1;
  1613. }
  1614. sub run_hooks ($$) {
  1615. # Calls the given sub for each hook of the given type,
  1616. # passing it the hook function to call.
  1617. my $type=shift;
  1618. my $sub=shift;
  1619. if (exists $hooks{$type}) {
  1620. my (@first, @middle, @last);
  1621. foreach my $id (keys %{$hooks{$type}}) {
  1622. if ($hooks{$type}{$id}{first}) {
  1623. push @first, $id;
  1624. }
  1625. elsif ($hooks{$type}{$id}{last}) {
  1626. push @last, $id;
  1627. }
  1628. else {
  1629. push @middle, $id;
  1630. }
  1631. }
  1632. foreach my $id (@first, @middle, @last) {
  1633. $sub->($hooks{$type}{$id}{call});
  1634. }
  1635. }
  1636. return 1;
  1637. }
  1638. sub rcs_update () {
  1639. $hooks{rcs}{rcs_update}{call}->(@_);
  1640. }
  1641. sub rcs_prepedit ($) {
  1642. $hooks{rcs}{rcs_prepedit}{call}->(@_);
  1643. }
  1644. sub rcs_commit (@) {
  1645. $hooks{rcs}{rcs_commit}{call}->(@_);
  1646. }
  1647. sub rcs_commit_staged (@) {
  1648. $hooks{rcs}{rcs_commit_staged}{call}->(@_);
  1649. }
  1650. sub rcs_add ($) {
  1651. $hooks{rcs}{rcs_add}{call}->(@_);
  1652. }
  1653. sub rcs_remove ($) {
  1654. $hooks{rcs}{rcs_remove}{call}->(@_);
  1655. }
  1656. sub rcs_rename ($$) {
  1657. $hooks{rcs}{rcs_rename}{call}->(@_);
  1658. }
  1659. sub rcs_recentchanges ($) {
  1660. $hooks{rcs}{rcs_recentchanges}{call}->(@_);
  1661. }
  1662. sub rcs_diff ($) {
  1663. $hooks{rcs}{rcs_diff}{call}->(@_);
  1664. }
  1665. sub rcs_getctime ($) {
  1666. $hooks{rcs}{rcs_getctime}{call}->(@_);
  1667. }
  1668. sub rcs_getmtime ($) {
  1669. $hooks{rcs}{rcs_getmtime}{call}->(@_);
  1670. }
  1671. sub rcs_receive () {
  1672. $hooks{rcs}{rcs_receive}{call}->();
  1673. }
  1674. sub add_depends ($$;$) {
  1675. my $page=shift;
  1676. my $pagespec=shift;
  1677. my $deptype=shift || $DEPEND_CONTENT;
  1678. # Is the pagespec a simple page name?
  1679. if ($pagespec =~ /$config{wiki_file_regexp}/ &&
  1680. $pagespec !~ /[\s*?()!]/) {
  1681. $depends_simple{$page}{lc $pagespec} |= $deptype;
  1682. return 1;
  1683. }
  1684. # Add explicit dependencies for influences.
  1685. my $sub=pagespec_translate($pagespec);
  1686. return unless defined $sub;
  1687. foreach my $p (keys %pagesources) {
  1688. my $r=$sub->($p, location => $page);
  1689. my $i=$r->influences;
  1690. my $static=$r->influences_static;
  1691. foreach my $k (keys %$i) {
  1692. next unless $r || $static || $k eq $page;
  1693. $depends_simple{$page}{lc $k} |= $i->{$k};
  1694. }
  1695. last if $static;
  1696. }
  1697. $depends{$page}{$pagespec} |= $deptype;
  1698. return 1;
  1699. }
  1700. sub deptype (@) {
  1701. my $deptype=0;
  1702. foreach my $type (@_) {
  1703. if ($type eq 'presence') {
  1704. $deptype |= $DEPEND_PRESENCE;
  1705. }
  1706. elsif ($type eq 'links') {
  1707. $deptype |= $DEPEND_LINKS;
  1708. }
  1709. elsif ($type eq 'content') {
  1710. $deptype |= $DEPEND_CONTENT;
  1711. }
  1712. }
  1713. return $deptype;
  1714. }
  1715. my $file_prune_regexp;
  1716. sub file_pruned ($) {
  1717. my $file=shift;
  1718. if (defined $config{include} && length $config{include}) {
  1719. return 0 if $file =~ m/$config{include}/;
  1720. }
  1721. if (! defined $file_prune_regexp) {
  1722. $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
  1723. $file_prune_regexp=qr/$file_prune_regexp/;
  1724. }
  1725. return $file =~ m/$file_prune_regexp/;
  1726. }
  1727. sub define_gettext () {
  1728. # If translation is needed, redefine the gettext function to do it.
  1729. # Otherwise, it becomes a quick no-op.
  1730. my $gettext_obj;
  1731. my $getobj;
  1732. if ((exists $ENV{LANG} && length $ENV{LANG}) ||
  1733. (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
  1734. (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
  1735. $getobj=sub {
  1736. $gettext_obj=eval q{
  1737. use Locale::gettext q{textdomain};
  1738. Locale::gettext->domain('ikiwiki')
  1739. };
  1740. };
  1741. }
  1742. no warnings 'redefine';
  1743. *gettext=sub {
  1744. $getobj->() if $getobj;
  1745. if ($gettext_obj) {
  1746. $gettext_obj->get(shift);
  1747. }
  1748. else {
  1749. return shift;
  1750. }
  1751. };
  1752. *ngettext=sub {
  1753. $getobj->() if $getobj;
  1754. if ($gettext_obj) {
  1755. $gettext_obj->nget(@_);
  1756. }
  1757. else {
  1758. return ($_[2] == 1 ? $_[0] : $_[1])
  1759. }
  1760. };
  1761. }
  1762. sub gettext {
  1763. define_gettext();
  1764. gettext(@_);
  1765. }
  1766. sub ngettext {
  1767. define_gettext();
  1768. ngettext(@_);
  1769. }
  1770. sub yesno ($) {
  1771. my $val=shift;
  1772. return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
  1773. }
  1774. sub inject {
  1775. # Injects a new function into the symbol table to replace an
  1776. # exported function.
  1777. my %params=@_;
  1778. # This is deep ugly perl foo, beware.
  1779. no strict;
  1780. no warnings;
  1781. if (! defined $params{parent}) {
  1782. $params{parent}='::';
  1783. $params{old}=\&{$params{name}};
  1784. $params{name}=~s/.*:://;
  1785. }
  1786. my $parent=$params{parent};
  1787. foreach my $ns (grep /^\w+::/, keys %{$parent}) {
  1788. $ns = $params{parent} . $ns;
  1789. inject(%params, parent => $ns) unless $ns eq '::main::';
  1790. *{$ns . $params{name}} = $params{call}
  1791. if exists ${$ns}{$params{name}} &&
  1792. \&{${$ns}{$params{name}}} == $params{old};
  1793. }
  1794. use strict;
  1795. use warnings;
  1796. }
  1797. sub add_link ($$;$) {
  1798. my $page=shift;
  1799. my $link=shift;
  1800. my $type=shift;
  1801. push @{$links{$page}}, $link
  1802. unless grep { $_ eq $link } @{$links{$page}};
  1803. if (defined $type) {
  1804. $typedlinks{$page}{$type}{$link} = 1;
  1805. }
  1806. }
  1807. sub add_autofile ($$$) {
  1808. my $file=shift;
  1809. my $plugin=shift;
  1810. my $generator=shift;
  1811. $autofiles{$file}{plugin}=$plugin;
  1812. $autofiles{$file}{generator}=$generator;
  1813. }
  1814. sub sortspec_translate ($$) {
  1815. my $spec = shift;
  1816. my $reverse = shift;
  1817. my $code = "";
  1818. my @data;
  1819. while ($spec =~ m{
  1820. \s*
  1821. (-?) # group 1: perhaps negated
  1822. \s*
  1823. ( # group 2: a word
  1824. \w+\([^\)]*\) # command(params)
  1825. |
  1826. [^\s]+ # or anything else
  1827. )
  1828. \s*
  1829. }gx) {
  1830. my $negated = $1;
  1831. my $word = $2;
  1832. my $params = undef;
  1833. if ($word =~ m/^(\w+)\((.*)\)$/) {
  1834. # command with parameters
  1835. $params = $2;
  1836. $word = $1;
  1837. }
  1838. elsif ($word !~ m/^\w+$/) {
  1839. error(sprintf(gettext("invalid sort type %s"), $word));
  1840. }
  1841. if (length $code) {
  1842. $code .= " || ";
  1843. }
  1844. if ($negated) {
  1845. $code .= "-";
  1846. }
  1847. if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
  1848. if (defined $params) {
  1849. push @data, $params;
  1850. $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
  1851. }
  1852. else {
  1853. $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
  1854. }
  1855. }
  1856. else {
  1857. error(sprintf(gettext("unknown sort type %s"), $word));
  1858. }
  1859. }
  1860. if (! length $code) {
  1861. # undefined sorting method... sort arbitrarily
  1862. return sub { 0 };
  1863. }
  1864. if ($reverse) {
  1865. $code="-($code)";
  1866. }
  1867. no warnings;
  1868. return eval 'sub { '.$code.' }';
  1869. }
  1870. sub pagespec_translate ($) {
  1871. my $spec=shift;
  1872. # Convert spec to perl code.
  1873. my $code="";
  1874. my @data;
  1875. while ($spec=~m{
  1876. \s* # ignore whitespace
  1877. ( # 1: match a single word
  1878. \! # !
  1879. |
  1880. \( # (
  1881. |
  1882. \) # )
  1883. |
  1884. \w+\([^\)]*\) # command(params)
  1885. |
  1886. [^\s()]+ # any other text
  1887. )
  1888. \s* # ignore whitespace
  1889. }gx) {
  1890. my $word=$1;
  1891. if (lc $word eq 'and') {
  1892. $code.=' &';
  1893. }
  1894. elsif (lc $word eq 'or') {
  1895. $code.=' |';
  1896. }
  1897. elsif ($word eq "(" || $word eq ")" || $word eq "!") {
  1898. $code.=' '.$word;
  1899. }
  1900. elsif ($word =~ /^(\w+)\((.*)\)$/) {
  1901. if (exists $IkiWiki::PageSpec::{"match_$1"}) {
  1902. push @data, $2;
  1903. $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
  1904. }
  1905. else {
  1906. push @data, qq{unknown function in pagespec "$word"};
  1907. $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
  1908. }
  1909. }
  1910. else {
  1911. push @data, $word;
  1912. $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
  1913. }
  1914. }
  1915. if (! length $code) {
  1916. $code="IkiWiki::FailReason->new('empty pagespec')";
  1917. }
  1918. no warnings;
  1919. return eval 'sub { my $page=shift; '.$code.' }';
  1920. }
  1921. sub pagespec_match ($$;@) {
  1922. my $page=shift;
  1923. my $spec=shift;
  1924. my @params=@_;
  1925. # Backwards compatability with old calling convention.
  1926. if (@params == 1) {
  1927. unshift @params, 'location';
  1928. }
  1929. my $sub=pagespec_translate($spec);
  1930. return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
  1931. if ! defined $sub;
  1932. return $sub->($page, @params);
  1933. }
  1934. sub pagespec_match_list ($$;@) {
  1935. my $page=shift;
  1936. my $pagespec=shift;
  1937. my %params=@_;
  1938. # Backwards compatability with old calling convention.
  1939. if (ref $page) {
  1940. print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
  1941. $params{list}=$page;
  1942. $page=$params{location}; # ugh!
  1943. }
  1944. my $sub=pagespec_translate($pagespec);
  1945. error "syntax error in pagespec \"$pagespec\""
  1946. if ! defined $sub;
  1947. my $sort=sortspec_translate($params{sort}, $params{reverse})
  1948. if defined $params{sort};
  1949. my @candidates;
  1950. if (exists $params{list}) {
  1951. @candidates=exists $params{filter}
  1952. ? grep { ! $params{filter}->($_) } @{$params{list}}
  1953. : @{$params{list}};
  1954. }
  1955. else {
  1956. @candidates=exists $params{filter}
  1957. ? grep { ! $params{filter}->($_) } keys %pagesources
  1958. : keys %pagesources;
  1959. }
  1960. # clear params, remainder is passed to pagespec
  1961. $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
  1962. my $num=$params{num};
  1963. delete @params{qw{num deptype reverse sort filter list}};
  1964. # when only the top matches will be returned, it's efficient to
  1965. # sort before matching to pagespec,
  1966. if (defined $num && defined $sort) {
  1967. @candidates=IkiWiki::SortSpec::sort_pages(
  1968. $sort, @candidates);
  1969. }
  1970. my @matches;
  1971. my $firstfail;
  1972. my $count=0;
  1973. my $accum=IkiWiki::SuccessReason->new();
  1974. foreach my $p (@candidates) {
  1975. my $r=$sub->($p, %params, location => $page);
  1976. error(sprintf(gettext("cannot match pages: %s"), $r))
  1977. if $r->isa("IkiWiki::ErrorReason");
  1978. unless ($r || $r->influences_static) {
  1979. $r->remove_influence($p);
  1980. }
  1981. $accum |= $r;
  1982. if ($r) {
  1983. push @matches, $p;
  1984. last if defined $num && ++$count == $num;
  1985. }
  1986. }
  1987. # Add simple dependencies for accumulated influences.
  1988. my $i=$accum->influences;
  1989. foreach my $k (keys %$i) {
  1990. $depends_simple{$page}{lc $k} |= $i->{$k};
  1991. }
  1992. # when all matches will be returned, it's efficient to
  1993. # sort after matching
  1994. if (! defined $num && defined $sort) {
  1995. return IkiWiki::SortSpec::sort_pages(
  1996. $sort, @matches);
  1997. }
  1998. else {
  1999. return @matches;
  2000. }
  2001. }
  2002. sub pagespec_valid ($) {
  2003. my $spec=shift;
  2004. return defined pagespec_translate($spec);
  2005. }
  2006. sub glob2re ($) {
  2007. my $re=quotemeta(shift);
  2008. $re=~s/\\\*/.*/g;
  2009. $re=~s/\\\?/./g;
  2010. return $re;
  2011. }
  2012. package IkiWiki::FailReason;
  2013. use overload (
  2014. '""' => sub { $_[0][0] },
  2015. '0+' => sub { 0 },
  2016. '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
  2017. '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
  2018. '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
  2019. fallback => 1,
  2020. );
  2021. our @ISA = 'IkiWiki::SuccessReason';
  2022. package IkiWiki::SuccessReason;
  2023. use overload (
  2024. '""' => sub { $_[0][0] },
  2025. '0+' => sub { 1 },
  2026. '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
  2027. '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
  2028. '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
  2029. fallback => 1,
  2030. );
  2031. sub new {
  2032. my $class = shift;
  2033. my $value = shift;
  2034. return bless [$value, {@_}], $class;
  2035. }
  2036. sub influences {
  2037. my $this=shift;
  2038. $this->[1]={@_} if @_;
  2039. my %i=%{$this->[1]};
  2040. delete $i{""};
  2041. return \%i;
  2042. }
  2043. sub influences_static {
  2044. return ! $_[0][1]->{""};
  2045. }
  2046. sub merge_influences {
  2047. my $this=shift;
  2048. my $other=shift;
  2049. my $anded=shift;
  2050. if (! $anded || (($this || %{$this->[1]}) &&
  2051. ($other || %{$other->[1]}))) {
  2052. foreach my $influence (keys %{$other->[1]}) {
  2053. $this->[1]{$influence} |= $other->[1]{$influence};
  2054. }
  2055. }
  2056. else {
  2057. # influence blocker
  2058. $this->[1]={};
  2059. }
  2060. }
  2061. sub remove_influence {
  2062. my $this=shift;
  2063. my $torm=shift;
  2064. delete $this->[1]{$torm};
  2065. }
  2066. package IkiWiki::ErrorReason;
  2067. our @ISA = 'IkiWiki::FailReason';
  2068. package IkiWiki::PageSpec;
  2069. sub derel ($$) {
  2070. my $path=shift;
  2071. my $from=shift;
  2072. if ($path =~ m!^\./!) {
  2073. $from=~s#/?[^/]+$## if defined $from;
  2074. $path=~s#^\./##;
  2075. $path="$from/$path" if defined $from && length $from;
  2076. }
  2077. return $path;
  2078. }
  2079. sub match_glob ($$;@) {
  2080. my $page=shift;
  2081. my $glob=shift;
  2082. my %params=@_;
  2083. $glob=derel($glob, $params{location});
  2084. my $regexp=IkiWiki::glob2re($glob);
  2085. if ($page=~/^$regexp$/i) {
  2086. if (! IkiWiki::isinternal($page) || $params{internal}) {
  2087. return IkiWiki::SuccessReason->new("$glob matches $page");
  2088. }
  2089. else {
  2090. return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
  2091. }
  2092. }
  2093. else {
  2094. return IkiWiki::FailReason->new("$glob does not match $page");
  2095. }
  2096. }
  2097. sub match_internal ($$;@) {
  2098. return match_glob(shift, shift, @_, internal => 1)
  2099. }
  2100. sub match_page ($$;@) {
  2101. my $page=shift;
  2102. my $match=match_glob($page, shift, @_);
  2103. if ($match && ! (exists $IkiWiki::pagesources{$page}
  2104. && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
  2105. return IkiWiki::FailReason->new("$page is not a page");
  2106. }
  2107. else {
  2108. return $match;
  2109. }
  2110. }
  2111. sub match_link ($$;@) {
  2112. my $page=shift;
  2113. my $link=lc(shift);
  2114. my %params=@_;
  2115. $link=derel($link, $params{location});
  2116. my $from=exists $params{location} ? $params{location} : '';
  2117. my $linktype=$params{linktype};
  2118. my $qualifier='';
  2119. if (defined $linktype) {
  2120. $qualifier=" with type $linktype";
  2121. }
  2122. my $links = $IkiWiki::links{$page};
  2123. return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2124. unless $links && @{$links};
  2125. my $bestlink = IkiWiki::bestlink($from, $link);
  2126. foreach my $p (@{$links}) {
  2127. next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
  2128. if (length $bestlink) {
  2129. if ($bestlink eq IkiWiki::bestlink($page, $p)) {
  2130. return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2131. }
  2132. }
  2133. else {
  2134. if (match_glob($p, $link, %params)) {
  2135. return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2136. }
  2137. my ($p_rel)=$p=~/^\/?(.*)/;
  2138. $link=~s/^\///;
  2139. if (match_glob($p_rel, $link, %params)) {
  2140. return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
  2141. }
  2142. }
  2143. }
  2144. return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
  2145. }
  2146. sub match_backlink ($$;@) {
  2147. my $ret=match_link($_[1], $_[0], @_);
  2148. $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
  2149. return $ret;
  2150. }
  2151. sub match_created_before ($$;@) {
  2152. my $page=shift;
  2153. my $testpage=shift;
  2154. my %params=@_;
  2155. $testpage=derel($testpage, $params{location});
  2156. if (exists $IkiWiki::pagectime{$testpage}) {
  2157. if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
  2158. return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2159. }
  2160. else {
  2161. return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2162. }
  2163. }
  2164. else {
  2165. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2166. }
  2167. }
  2168. sub match_created_after ($$;@) {
  2169. my $page=shift;
  2170. my $testpage=shift;
  2171. my %params=@_;
  2172. $testpage=derel($testpage, $params{location});
  2173. if (exists $IkiWiki::pagectime{$testpage}) {
  2174. if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
  2175. return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2176. }
  2177. else {
  2178. return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2179. }
  2180. }
  2181. else {
  2182. return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
  2183. }
  2184. }
  2185. sub match_creation_day ($$;@) {
  2186. if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
  2187. return IkiWiki::SuccessReason->new('creation_day matched');
  2188. }
  2189. else {
  2190. return IkiWiki::FailReason->new('creation_day did not match');
  2191. }
  2192. }
  2193. sub match_creation_month ($$;@) {
  2194. if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
  2195. return IkiWiki::SuccessReason->new('creation_month matched');
  2196. }
  2197. else {
  2198. return IkiWiki::FailReason->new('creation_month did not match');
  2199. }
  2200. }
  2201. sub match_creation_year ($$;@) {
  2202. if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
  2203. return IkiWiki::SuccessReason->new('creation_year matched');
  2204. }
  2205. else {
  2206. return IkiWiki::FailReason->new('creation_year did not match');
  2207. }
  2208. }
  2209. sub match_user ($$;@) {
  2210. shift;
  2211. my $user=shift;
  2212. my %params=@_;
  2213. my $regexp=IkiWiki::glob2re($user);
  2214. if (! exists $params{user}) {
  2215. return IkiWiki::ErrorReason->new("no user specified");
  2216. }
  2217. if (defined $params{user} && $params{user}=~/^$regexp$/i) {
  2218. return IkiWiki::SuccessReason->new("user is $user");
  2219. }
  2220. elsif (! defined $params{user}) {
  2221. return IkiWiki::FailReason->new("not logged in");
  2222. }
  2223. else {
  2224. return IkiWiki::FailReason->new("user is $params{user}, not $user");
  2225. }
  2226. }
  2227. sub match_admin ($$;@) {
  2228. shift;
  2229. shift;
  2230. my %params=@_;
  2231. if (! exists $params{user}) {
  2232. return IkiWiki::ErrorReason->new("no user specified");
  2233. }
  2234. if (defined $params{user} && IkiWiki::is_admin($params{user})) {
  2235. return IkiWiki::SuccessReason->new("user is an admin");
  2236. }
  2237. elsif (! defined $params{user}) {
  2238. return IkiWiki::FailReason->new("not logged in");
  2239. }
  2240. else {
  2241. return IkiWiki::FailReason->new("user is not an admin");
  2242. }
  2243. }
  2244. sub match_ip ($$;@) {
  2245. shift;
  2246. my $ip=shift;
  2247. my %params=@_;
  2248. if (! exists $params{ip}) {
  2249. return IkiWiki::ErrorReason->new("no IP specified");
  2250. }
  2251. if (defined $params{ip} && lc $params{ip} eq lc $ip) {
  2252. return IkiWiki::SuccessReason->new("IP is $ip");
  2253. }
  2254. else {
  2255. return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
  2256. }
  2257. }
  2258. package IkiWiki::SortSpec;
  2259. # This is in the SortSpec namespace so that the $a and $b that sort() uses
  2260. # are easily available in this namespace, for cmp functions to use them.
  2261. sub sort_pages {
  2262. my $f=shift;
  2263. sort $f @_
  2264. }
  2265. sub cmp_title {
  2266. IkiWiki::pagetitle(IkiWiki::basename($a))
  2267. cmp
  2268. IkiWiki::pagetitle(IkiWiki::basename($b))
  2269. }
  2270. sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
  2271. sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
  2272. 1