summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: d6057c101278d3bfb9dae3b52119bb99dc6bf672 (plain)
  1. #!/usr/bin/perl -T
  2. $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
  3. use warnings;
  4. use strict;
  5. use Memoize;
  6. use File::Spec;
  7. use HTML::Template;
  8. use Getopt::Long;
  9. my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
  10. my %config=( #{{{
  11. wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
  12. wiki_link_regexp => qr/\[\[([^\s]+)\]\]/,
  13. wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
  14. verbose => 0,
  15. wikiname => "wiki",
  16. default_pageext => ".mdwn",
  17. cgi => 0,
  18. svn => 1,
  19. url => '',
  20. cgiurl => '',
  21. historyurl => '',
  22. anonok => 0,
  23. rebuild => 0,
  24. wrapper => undef,
  25. wrappermode => undef,
  26. srcdir => undef,
  27. destdir => undef,
  28. templatedir => undef,
  29. setup => undef,
  30. ); #}}}
  31. GetOptions( #{{{
  32. "setup=s" => \$config{setup},
  33. "wikiname=s" => \$config{wikiname},
  34. "verbose|v!" => \$config{verbose},
  35. "rebuild!" => \$config{rebuild},
  36. "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
  37. "wrappermode=i" => \$config{wrappermode},
  38. "svn!" => \$config{svn},
  39. "anonok!" => \$config{anonok},
  40. "cgi!" => \$config{cgi},
  41. "url=s" => \$config{url},
  42. "cgiurl=s" => \$config{cgiurl},
  43. "historyurl=s" => \$config{historyurl},
  44. "exclude=s@" => sub {
  45. $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
  46. },
  47. ) || usage();
  48. if (! $config{setup}) {
  49. usage() unless @ARGV == 3;
  50. $config{srcdir} = possibly_foolish_untaint(shift);
  51. $config{templatedir} = possibly_foolish_untaint(shift);
  52. $config{destdir} = possibly_foolish_untaint(shift);
  53. if ($config{cgi} && ! length $config{url}) {
  54. error("Must specify url to wiki with --url when using --cgi");
  55. }
  56. }
  57. #}}}
  58. sub usage { #{{{
  59. die "usage: ikiwiki [options] source templates dest\n";
  60. } #}}}
  61. sub error { #{{{
  62. if ($config{cgi}) {
  63. print "Content-type: text/html\n\n";
  64. print misctemplate("Error", "<p>Error: @_</p>");
  65. }
  66. die @_;
  67. } #}}}
  68. sub debug ($) { #{{{
  69. return unless $config{verbose};
  70. if (! $config{cgi}) {
  71. print "@_\n";
  72. }
  73. else {
  74. print STDERR "@_\n";
  75. }
  76. } #}}}
  77. sub mtime ($) { #{{{
  78. my $page=shift;
  79. return (stat($page))[9];
  80. } #}}}
  81. sub possibly_foolish_untaint { #{{{
  82. my $tainted=shift;
  83. my ($untainted)=$tainted=~/(.*)/;
  84. return $untainted;
  85. } #}}}
  86. sub basename ($) { #{{{
  87. my $file=shift;
  88. $file=~s!.*/!!;
  89. return $file;
  90. } #}}}
  91. sub dirname ($) { #{{{
  92. my $file=shift;
  93. $file=~s!/?[^/]+$!!;
  94. return $file;
  95. } #}}}
  96. sub pagetype ($) { #{{{
  97. my $page=shift;
  98. if ($page =~ /\.mdwn$/) {
  99. return ".mdwn";
  100. }
  101. else {
  102. return "unknown";
  103. }
  104. } #}}}
  105. sub pagename ($) { #{{{
  106. my $file=shift;
  107. my $type=pagetype($file);
  108. my $page=$file;
  109. $page=~s/\Q$type\E*$// unless $type eq 'unknown';
  110. return $page;
  111. } #}}}
  112. sub htmlpage ($) { #{{{
  113. my $page=shift;
  114. return $page.".html";
  115. } #}}}
  116. sub readfile ($) { #{{{
  117. my $file=shift;
  118. local $/=undef;
  119. open (IN, "$file") || error("failed to read $file: $!");
  120. my $ret=<IN>;
  121. close IN;
  122. return $ret;
  123. } #}}}
  124. sub writefile ($$) { #{{{
  125. my $file=shift;
  126. my $content=shift;
  127. my $dir=dirname($file);
  128. if (! -d $dir) {
  129. my $d="";
  130. foreach my $s (split(m!/+!, $dir)) {
  131. $d.="$s/";
  132. if (! -d $d) {
  133. mkdir($d) || error("failed to create directory $d: $!");
  134. }
  135. }
  136. }
  137. open (OUT, ">$file") || error("failed to write $file: $!");
  138. print OUT $content;
  139. close OUT;
  140. } #}}}
  141. sub findlinks ($) { #{{{
  142. my $content=shift;
  143. my @links;
  144. while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
  145. push @links, lc($1);
  146. }
  147. return @links;
  148. } #}}}
  149. sub bestlink ($$) { #{{{
  150. # Given a page and the text of a link on the page, determine which
  151. # existing page that link best points to. Prefers pages under a
  152. # subdirectory with the same name as the source page, failing that
  153. # goes down the directory tree to the base looking for matching
  154. # pages.
  155. my $page=shift;
  156. my $link=lc(shift);
  157. my $cwd=$page;
  158. do {
  159. my $l=$cwd;
  160. $l.="/" if length $l;
  161. $l.=$link;
  162. if (exists $links{$l}) {
  163. #debug("for $page, \"$link\", use $l");
  164. return $l;
  165. }
  166. } while $cwd=~s!/?[^/]+$!!;
  167. #print STDERR "warning: page $page, broken link: $link\n";
  168. return "";
  169. } #}}}
  170. sub isinlinableimage ($) { #{{{
  171. my $file=shift;
  172. $file=~/\.(png|gif|jpg|jpeg)$/;
  173. } #}}}
  174. sub htmllink { #{{{
  175. my $page=shift;
  176. my $link=shift;
  177. my $noimageinline=shift; # don't turn links into inline html images
  178. my $createsubpage=shift; # force creation of a subpage if page DNE
  179. my $bestlink=bestlink($page, $link);
  180. return $link if length $bestlink && $page eq $bestlink;
  181. # TODO BUG: %renderedfiles may not have it, if the linked to page
  182. # was also added and isn't yet rendered! Note that this bug is
  183. # masked by the bug mentioned below that makes all new files
  184. # be rendered twice.
  185. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  186. $bestlink=htmlpage($bestlink);
  187. }
  188. if (! grep { $_ eq $bestlink } values %renderedfiles) {
  189. if (! $createsubpage) {
  190. return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
  191. }
  192. else {
  193. return "<a href=\"$config{cgiurl}?do=create&page=$page/$link\">?</a>$link"
  194. }
  195. }
  196. $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
  197. if (! $noimageinline && isinlinableimage($bestlink)) {
  198. return "<img src=\"$bestlink\">";
  199. }
  200. return "<a href=\"$bestlink\">$link</a>";
  201. } #}}}
  202. sub linkify ($$) { #{{{
  203. my $content=shift;
  204. my $file=shift;
  205. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  206. $1 ? "[[$2]]" : htmllink(pagename($file), $2)
  207. }eg;
  208. return $content;
  209. } #}}}
  210. sub htmlize ($$) { #{{{
  211. my $type=shift;
  212. my $content=shift;
  213. if (! $INC{"/usr/bin/markdown"}) {
  214. no warnings 'once';
  215. $blosxom::version="is a proper perl module too much to ask?";
  216. use warnings 'all';
  217. do "/usr/bin/markdown";
  218. }
  219. if ($type eq '.mdwn') {
  220. return Markdown::Markdown($content);
  221. }
  222. else {
  223. error("htmlization of $type not supported");
  224. }
  225. } #}}}
  226. sub backlinks ($) { #{{{
  227. my $page=shift;
  228. my @links;
  229. foreach my $p (keys %links) {
  230. next if bestlink($page, $p) eq $page;
  231. if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
  232. my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
  233. # Trim common dir prefixes from both pages.
  234. my $p_trimmed=$p;
  235. my $page_trimmed=$page;
  236. my $dir;
  237. 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
  238. defined $dir &&
  239. $p_trimmed=~s/^\Q$dir\E// &&
  240. $page_trimmed=~s/^\Q$dir\E//;
  241. push @links, { url => $href, page => $p_trimmed };
  242. }
  243. }
  244. return sort { $a->{page} cmp $b->{page} } @links;
  245. } #}}}
  246. sub parentlinks ($) { #{{{
  247. my $page=shift;
  248. my @ret;
  249. my $pagelink="";
  250. my $path="";
  251. my $skip=1;
  252. foreach my $dir (reverse split("/", $page)) {
  253. if (! $skip) {
  254. $path.="../";
  255. unshift @ret, { url => "$path$dir.html", page => $dir };
  256. }
  257. else {
  258. $skip=0;
  259. }
  260. }
  261. unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
  262. return @ret;
  263. } #}}}
  264. sub indexlink () { #{{{
  265. return "<a href=\"$config{url}\">$config{wikiname}</a>";
  266. } #}}}
  267. sub finalize ($$) { #{{{
  268. my $content=shift;
  269. my $page=shift;
  270. my $title=basename($page);
  271. $title=~s/_/ /g;
  272. my $template=HTML::Template->new(blind_cache => 1,
  273. filename => "$config{templatedir}/page.tmpl");
  274. if (length $config{cgiurl}) {
  275. $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
  276. if ($config{svn}) {
  277. $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
  278. }
  279. }
  280. if (length $config{historyurl}) {
  281. my $u=$config{historyurl};
  282. $u=~s/\[\[\]\]/$pagesources{$page}/g;
  283. $template->param(historyurl => $u);
  284. }
  285. $template->param(
  286. title => $title,
  287. wikiname => $config{wikiname},
  288. parentlinks => [parentlinks($page)],
  289. content => $content,
  290. backlinks => [backlinks($page)],
  291. discussionlink => htmllink($page, "Discussion", 1, 1),
  292. );
  293. return $template->output;
  294. } #}}}
  295. sub check_overwrite ($$) { #{{{
  296. # Important security check. Make sure to call this before saving
  297. # any files to the source directory.
  298. my $dest=shift;
  299. my $src=shift;
  300. if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
  301. error("$dest already exists and was rendered from ".
  302. join(" ",(grep { $renderedfiles{$_} eq $dest } keys
  303. %renderedfiles)).
  304. ", before, so not rendering from $src");
  305. }
  306. } #}}}
  307. sub render ($) { #{{{
  308. my $file=shift;
  309. my $type=pagetype($file);
  310. my $content=readfile("$config{srcdir}/$file");
  311. if ($type ne 'unknown') {
  312. my $page=pagename($file);
  313. $links{$page}=[findlinks($content)];
  314. $content=linkify($content, $file);
  315. $content=htmlize($type, $content);
  316. $content=finalize($content, $page);
  317. check_overwrite("$config{destdir}/".htmlpage($page), $page);
  318. writefile("$config{destdir}/".htmlpage($page), $content);
  319. $oldpagemtime{$page}=time;
  320. $renderedfiles{$page}=htmlpage($page);
  321. }
  322. else {
  323. $links{$file}=[];
  324. check_overwrite("$config{destdir}/$file", $file);
  325. writefile("$config{destdir}/$file", $content);
  326. $oldpagemtime{$file}=time;
  327. $renderedfiles{$file}=$file;
  328. }
  329. } #}}}
  330. sub loadindex () { #{{{
  331. open (IN, "$config{srcdir}/.ikiwiki/index") || return;
  332. while (<IN>) {
  333. $_=possibly_foolish_untaint($_);
  334. chomp;
  335. my ($mtime, $file, $rendered, @links)=split(' ', $_);
  336. my $page=pagename($file);
  337. $pagesources{$page}=$file;
  338. $oldpagemtime{$page}=$mtime;
  339. $oldlinks{$page}=[@links];
  340. $links{$page}=[@links];
  341. $renderedfiles{$page}=$rendered;
  342. }
  343. close IN;
  344. } #}}}
  345. sub saveindex () { #{{{
  346. if (! -d "$config{srcdir}/.ikiwiki") {
  347. mkdir("$config{srcdir}/.ikiwiki");
  348. }
  349. open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
  350. foreach my $page (keys %oldpagemtime) {
  351. print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
  352. join(" ", @{$links{$page}})."\n"
  353. if $oldpagemtime{$page};
  354. }
  355. close OUT;
  356. } #}}}
  357. sub rcs_update () { #{{{
  358. if (-d "$config{srcdir}/.svn") {
  359. if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
  360. warn("svn update failed\n");
  361. }
  362. }
  363. } #}}}
  364. sub rcs_commit ($) { #{{{
  365. my $message=shift;
  366. if (-d "$config{srcdir}/.svn") {
  367. if (system("svn", "commit", "--quiet", "-m",
  368. possibly_foolish_untaint($message),
  369. $config{srcdir}) != 0) {
  370. warn("svn commit failed\n");
  371. }
  372. }
  373. } #}}}
  374. sub rcs_add ($) { #{{{
  375. my $file=shift;
  376. if (-d "$config{srcdir}/.svn") {
  377. my $parent=dirname($file);
  378. while (! -d "$config{srcdir}/$parent/.svn") {
  379. $file=$parent;
  380. $parent=dirname($file);
  381. }
  382. if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
  383. warn("svn add failed\n");
  384. }
  385. }
  386. } #}}}
  387. sub rcs_recentchanges ($) { #{{{
  388. my $num=shift;
  389. my @ret;
  390. eval q{use Date::Parse};
  391. eval q{use Time::Duration};
  392. if (-d "$config{srcdir}/.svn") {
  393. my $info=`LANG=C svn info $config{srcdir}`;
  394. my ($svn_url)=$info=~/^URL: (.*)$/m;
  395. # FIXME: currently assumes that the wiki is somewhere
  396. # under trunk in svn, doesn't support other layouts.
  397. my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
  398. my $div=qr/^--------------------+$/;
  399. my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
  400. my $state='start';
  401. my ($rev, $user, $when, @pages, @message);
  402. foreach (`LANG=C svn log -v '$svn_url'`) {
  403. chomp;
  404. if ($state eq 'start' && /$div/) {
  405. $state='header';
  406. }
  407. elsif ($state eq 'header' && /$infoline/) {
  408. $rev=$1;
  409. $user=$2;
  410. $when=concise(ago(time - str2time($3)));
  411. }
  412. elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
  413. push @pages, { link => htmllink("", pagename($1), 1) }
  414. if length $1;
  415. }
  416. elsif ($state eq 'header' && /^$/) {
  417. $state='body';
  418. }
  419. elsif ($state eq 'body' && /$div/) {
  420. my $committype="web";
  421. if (defined $message[0] &&
  422. $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
  423. $user="$1";
  424. $message[0]->{line}=$2;
  425. }
  426. else {
  427. $committype="svn";
  428. }
  429. push @ret, { rev => $rev,
  430. user => htmllink("", $user, 1),
  431. committype => $committype,
  432. when => $when, message => [@message],
  433. pages => [@pages] } if @pages;
  434. return @ret if @ret >= $num;
  435. $state='header';
  436. $rev=$user=$when=undef;
  437. @pages=@message=();
  438. }
  439. elsif ($state eq 'body') {
  440. push @message, {line => $_},
  441. }
  442. }
  443. }
  444. return @ret;
  445. } #}}}
  446. sub prune ($) { #{{{
  447. my $file=shift;
  448. unlink($file);
  449. my $dir=dirname($file);
  450. while (rmdir($dir)) {
  451. $dir=dirname($dir);
  452. }
  453. } #}}}
  454. sub refresh () { #{{{
  455. # Find existing pages.
  456. my %exists;
  457. my @files;
  458. eval q{use File::Find};
  459. find({
  460. no_chdir => 1,
  461. wanted => sub {
  462. if (/$config{wiki_file_prune_regexp}/) {
  463. no warnings 'once';
  464. $File::Find::prune=1;
  465. use warnings "all";
  466. }
  467. elsif (! -d $_) {
  468. my ($f)=/$config{wiki_file_regexp}/; # untaint
  469. if (! defined $f) {
  470. warn("skipping bad filename $_\n");
  471. }
  472. else {
  473. $f=~s/^\Q$config{srcdir}\E\/?//;
  474. push @files, $f;
  475. $exists{pagename($f)}=1;
  476. }
  477. }
  478. },
  479. }, $config{srcdir});
  480. my %rendered;
  481. # check for added or removed pages
  482. my @add;
  483. foreach my $file (@files) {
  484. my $page=pagename($file);
  485. if (! $oldpagemtime{$page}) {
  486. debug("new page $page");
  487. push @add, $file;
  488. $links{$page}=[];
  489. $pagesources{$page}=$file;
  490. }
  491. }
  492. my @del;
  493. foreach my $page (keys %oldpagemtime) {
  494. if (! $exists{$page}) {
  495. debug("removing old page $page");
  496. push @del, $renderedfiles{$page};
  497. prune($config{destdir}."/".$renderedfiles{$page});
  498. delete $renderedfiles{$page};
  499. $oldpagemtime{$page}=0;
  500. delete $pagesources{$page};
  501. }
  502. }
  503. # render any updated files
  504. foreach my $file (@files) {
  505. my $page=pagename($file);
  506. if (! exists $oldpagemtime{$page} ||
  507. mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
  508. debug("rendering changed file $file");
  509. render($file);
  510. $rendered{$file}=1;
  511. }
  512. }
  513. # if any files were added or removed, check to see if each page
  514. # needs an update due to linking to them
  515. # TODO: inefficient; pages may get rendered above and again here;
  516. # problem is the bestlink may have changed and we won't know until
  517. # now
  518. if (@add || @del) {
  519. FILE: foreach my $file (@files) {
  520. my $page=pagename($file);
  521. foreach my $f (@add, @del) {
  522. my $p=pagename($f);
  523. foreach my $link (@{$links{$page}}) {
  524. if (bestlink($page, $link) eq $p) {
  525. debug("rendering $file, which links to $p");
  526. render($file);
  527. $rendered{$file}=1;
  528. next FILE;
  529. }
  530. }
  531. }
  532. }
  533. }
  534. # handle backlinks; if a page has added/removed links, update the
  535. # pages it links to
  536. # TODO: inefficient; pages may get rendered above and again here;
  537. # problem is the backlinks could be wrong in the first pass render
  538. # above
  539. if (%rendered) {
  540. my %linkchanged;
  541. foreach my $file (keys %rendered, @del) {
  542. my $page=pagename($file);
  543. if (exists $links{$page}) {
  544. foreach my $link (@{$links{$page}}) {
  545. $link=bestlink($page, $link);
  546. if (length $link &&
  547. ! exists $oldlinks{$page} ||
  548. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  549. $linkchanged{$link}=1;
  550. }
  551. }
  552. }
  553. if (exists $oldlinks{$page}) {
  554. foreach my $link (@{$oldlinks{$page}}) {
  555. $link=bestlink($page, $link);
  556. if (length $link &&
  557. ! exists $links{$page} ||
  558. ! grep { $_ eq $link } @{$links{$page}}) {
  559. $linkchanged{$link}=1;
  560. }
  561. }
  562. }
  563. }
  564. foreach my $link (keys %linkchanged) {
  565. my $linkfile=$pagesources{$link};
  566. if (defined $linkfile) {
  567. debug("rendering $linkfile, to update its backlinks");
  568. render($linkfile);
  569. }
  570. }
  571. }
  572. } #}}}
  573. sub gen_wrapper (@) { #{{{
  574. my %config=(@_);
  575. eval q{use Cwd 'abs_path'};
  576. $config{srcdir}=abs_path($config{srcdir});
  577. $config{destdir}=abs_path($config{destdir});
  578. my $this=abs_path($0);
  579. if (! -x $this) {
  580. error("$this doesn't seem to be executable");
  581. }
  582. if ($config{setup}) {
  583. error("cannot create a wrapper that uses a setup file");
  584. }
  585. my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
  586. "--wikiname=$config{wikiname}");
  587. push @params, "--verbose" if $config{verbose};
  588. push @params, "--rebuild" if $config{rebuild};
  589. push @params, "--nosvn" if !$config{svn};
  590. push @params, "--cgi" if $config{cgi};
  591. push @params, "--url=$config{url}" if length $config{url};
  592. push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
  593. push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
  594. push @params, "--anonok" if $config{anonok};
  595. my $params=join(" ", @params);
  596. my $call='';
  597. foreach my $p ($this, $this, @params) {
  598. $call.=qq{"$p", };
  599. }
  600. $call.="NULL";
  601. my @envsave;
  602. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  603. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  604. HTTP_COOKIE} if $config{cgi};
  605. my $envsave="";
  606. foreach my $var (@envsave) {
  607. $envsave.=<<"EOF"
  608. if ((s=getenv("$var")))
  609. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  610. EOF
  611. }
  612. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  613. print OUT <<"EOF";
  614. /* A wrapper for ikiwiki, can be safely made suid. */
  615. #define _GNU_SOURCE
  616. #include <stdio.h>
  617. #include <unistd.h>
  618. #include <stdlib.h>
  619. #include <string.h>
  620. extern char **environ;
  621. int main (int argc, char **argv) {
  622. /* Sanitize environment. */
  623. char *s;
  624. char *newenviron[$#envsave+3];
  625. int i=0;
  626. $envsave
  627. newenviron[i++]="HOME=$ENV{HOME}";
  628. newenviron[i]=NULL;
  629. environ=newenviron;
  630. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  631. printf("$params\\n");
  632. exit(0);
  633. }
  634. execl($call);
  635. perror("failed to run $this");
  636. exit(1);
  637. }
  638. EOF
  639. close OUT;
  640. if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
  641. error("failed to compile ikiwiki-wrap.c");
  642. }
  643. unlink("ikiwiki-wrap.c");
  644. if (defined $config{wrappermode} &&
  645. ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
  646. error("chmod $config{wrapper}: $!");
  647. }
  648. print "successfully generated $config{wrapper}\n";
  649. } #}}}
  650. sub misctemplate ($$) { #{{{
  651. my $title=shift;
  652. my $pagebody=shift;
  653. my $template=HTML::Template->new(
  654. filename => "$config{templatedir}/misc.tmpl"
  655. );
  656. $template->param(
  657. title => $title,
  658. indexlink => indexlink(),
  659. wikiname => $config{wikiname},
  660. pagebody => $pagebody,
  661. );
  662. return $template->output;
  663. }#}}}
  664. sub cgi_recentchanges ($) { #{{{
  665. my $q=shift;
  666. my $template=HTML::Template->new(
  667. filename => "$config{templatedir}/recentchanges.tmpl"
  668. );
  669. $template->param(
  670. title => "RecentChanges",
  671. indexlink => indexlink(),
  672. wikiname => $config{wikiname},
  673. changelog => [rcs_recentchanges(100)],
  674. );
  675. print $q->header, $template->output;
  676. } #}}}
  677. sub userinfo_get ($$) { #{{{
  678. my $user=shift;
  679. my $field=shift;
  680. eval q{use Storable};
  681. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  682. if (! defined $userdata || ! ref $userdata ||
  683. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  684. return "";
  685. }
  686. return $userdata->{$user}->{$field};
  687. } #}}}
  688. sub userinfo_set ($$) { #{{{
  689. my $user=shift;
  690. my $info=shift;
  691. eval q{use Storable};
  692. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  693. if (! defined $userdata || ! ref $userdata) {
  694. $userdata={};
  695. }
  696. $userdata->{$user}=$info;
  697. my $oldmask=umask(077);
  698. my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
  699. umask($oldmask);
  700. return $ret;
  701. } #}}}
  702. sub cgi_signin ($$) { #{{{
  703. my $q=shift;
  704. my $session=shift;
  705. eval q{use CGI::FormBuilder};
  706. my $form = CGI::FormBuilder->new(
  707. title => "$config{wikiname} signin",
  708. fields => [qw(do page from name password confirm_password email)],
  709. header => 1,
  710. method => 'POST',
  711. validate => {
  712. confirm_password => {
  713. perl => q{eq $form->field("password")},
  714. },
  715. email => 'EMAIL',
  716. },
  717. required => 'NONE',
  718. javascript => 0,
  719. params => $q,
  720. action => $q->request_uri,
  721. header => 0,
  722. template => (-e "$config{templatedir}/signin.tmpl" ?
  723. "$config{templatedir}/signin.tmpl" : "")
  724. );
  725. $form->field(name => "name", required => 0);
  726. $form->field(name => "do", type => "hidden");
  727. $form->field(name => "page", type => "hidden");
  728. $form->field(name => "from", type => "hidden");
  729. $form->field(name => "password", type => "password", required => 0);
  730. $form->field(name => "confirm_password", type => "password", required => 0);
  731. $form->field(name => "email", required => 0);
  732. if ($q->param("do") ne "signin") {
  733. $form->text("You need to log in before you can edit pages.");
  734. }
  735. if ($form->submitted) {
  736. # Set required fields based on how form was submitted.
  737. my %required=(
  738. "Login" => [qw(name password)],
  739. "Register" => [qw(name password confirm_password email)],
  740. "Mail Password" => [qw(name)],
  741. );
  742. foreach my $opt (@{$required{$form->submitted}}) {
  743. $form->field(name => $opt, required => 1);
  744. }
  745. # Validate password differently depending on how
  746. # form was submitted.
  747. if ($form->submitted eq 'Login') {
  748. $form->field(
  749. name => "password",
  750. validate => sub {
  751. length $form->field("name") &&
  752. shift eq userinfo_get($form->field("name"), 'password');
  753. },
  754. );
  755. $form->field(name => "name", validate => '/^\w+$/');
  756. }
  757. else {
  758. $form->field(name => "password", validate => 'VALUE');
  759. }
  760. # And make sure the entered name exists when logging
  761. # in or sending email, and does not when registering.
  762. if ($form->submitted eq 'Register') {
  763. $form->field(
  764. name => "name",
  765. validate => sub {
  766. my $name=shift;
  767. length $name &&
  768. ! userinfo_get($name, "regdate");
  769. },
  770. );
  771. }
  772. else {
  773. $form->field(
  774. name => "name",
  775. validate => sub {
  776. my $name=shift;
  777. length $name &&
  778. userinfo_get($name, "regdate");
  779. },
  780. );
  781. }
  782. }
  783. else {
  784. # First time settings.
  785. $form->field(name => "name", comment => "use FirstnameLastName");
  786. $form->field(name => "confirm_password", comment => "(only needed");
  787. $form->field(name => "email", comment => "for registration)");
  788. if ($session->param("name")) {
  789. $form->field(name => "name", value => $session->param("name"));
  790. }
  791. }
  792. if ($form->submitted && $form->validate) {
  793. if ($form->submitted eq 'Login') {
  794. $session->param("name", $form->field("name"));
  795. if (defined $form->field("do") &&
  796. $form->field("do") ne 'signin') {
  797. print $q->redirect(
  798. "$config{cgiurl}?do=".$form->field("do").
  799. "&page=".$form->field("page").
  800. "&from=".$form->field("from"));;
  801. }
  802. else {
  803. print $q->redirect($config{url});
  804. }
  805. }
  806. elsif ($form->submitted eq 'Register') {
  807. my $user_name=$form->field('name');
  808. if (userinfo_set($user_name, {
  809. 'email' => $form->field('email'),
  810. 'password' => $form->field('password'),
  811. 'regdate' => time
  812. })) {
  813. $form->field(name => "confirm_password", type => "hidden");
  814. $form->field(name => "email", type => "hidden");
  815. $form->text("Registration successful. Now you can Login.");
  816. print $session->header();
  817. print misctemplate($form->title, $form->render(submit => ["Login"]));
  818. }
  819. else {
  820. error("Error saving registration.");
  821. }
  822. }
  823. elsif ($form->submitted eq 'Mail Password') {
  824. my $user_name=$form->field("name");
  825. my $template=HTML::Template->new(
  826. filename => "$config{templatedir}/passwordmail.tmpl"
  827. );
  828. $template->param(
  829. user_name => $user_name,
  830. user_password => userinfo_get($user_name, "password"),
  831. wikiurl => $config{url},
  832. wikiname => $config{wikiname},
  833. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  834. );
  835. eval q{use Mail::Sendmail};
  836. my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
  837. sendmail(
  838. To => userinfo_get($user_name, "email"),
  839. From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
  840. Subject => "$config{wikiname} information",
  841. Message => $template->output,
  842. ) or error("Failed to send mail");
  843. $form->text("Your password has been emailed to you.");
  844. $form->field(name => "name", required => 0);
  845. print $session->header();
  846. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  847. }
  848. }
  849. else {
  850. print $session->header();
  851. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  852. }
  853. } #}}}
  854. sub cgi_editpage ($$) { #{{{
  855. my $q=shift;
  856. my $session=shift;
  857. eval q{use CGI::FormBuilder};
  858. my $form = CGI::FormBuilder->new(
  859. fields => [qw(do from page content comments)],
  860. header => 1,
  861. method => 'POST',
  862. validate => {
  863. content => '/.+/',
  864. },
  865. required => [qw{content}],
  866. javascript => 0,
  867. params => $q,
  868. action => $q->request_uri,
  869. table => 0,
  870. template => "$config{templatedir}/editpage.tmpl"
  871. );
  872. my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
  873. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  874. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  875. error("bad page name");
  876. }
  877. $page=lc($page);
  878. $form->field(name => "do", type => 'hidden');
  879. $form->field(name => "from", type => 'hidden');
  880. $form->field(name => "page", value => "$page", force => 1);
  881. $form->field(name => "comments", type => "text", size => 80);
  882. $form->field(name => "content", type => "textarea", rows => 20,
  883. cols => 80);
  884. if ($form->submitted eq "Cancel") {
  885. print $q->redirect("$config{url}/".htmlpage($page));
  886. return;
  887. }
  888. if (! $form->submitted || ! $form->validate) {
  889. if ($form->field("do") eq "create") {
  890. if (exists $pagesources{lc($page)}) {
  891. # hmm, someone else made the page in the
  892. # meantime?
  893. print $q->redirect("$config{url}/".htmlpage($page));
  894. return;
  895. }
  896. my @page_locs;
  897. my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
  898. if (! defined $from || ! length $from ||
  899. $from ne $form->param('from') ||
  900. $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
  901. @page_locs=$page;
  902. }
  903. else {
  904. my $dir=$from."/";
  905. $dir=~s![^/]+/$!!;
  906. push @page_locs, $dir.$page;
  907. push @page_locs, "$from/$page";
  908. while (length $dir) {
  909. $dir=~s![^/]+/$!!;
  910. push @page_locs, $dir.$page;
  911. }
  912. }
  913. $form->tmpl_param("page_select", 1);
  914. $form->field(name => "page", type => 'select',
  915. options => \@page_locs);
  916. $form->title("creating $page");
  917. }
  918. elsif ($form->field("do") eq "edit") {
  919. my $content="";
  920. if (exists $pagesources{lc($page)}) {
  921. $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
  922. $content=~s/\n/\r\n/g;
  923. }
  924. $form->tmpl_param("page_select", 0);
  925. $form->field(name => "content", value => $content,
  926. force => 1);
  927. $form->field(name => "page", type => 'hidden');
  928. $form->title("editing $page");
  929. }
  930. $form->tmpl_param("can_commit", $config{svn});
  931. $form->tmpl_param("indexlink", indexlink());
  932. print $form->render(submit => ["Save Page", "Cancel"]);
  933. }
  934. else {
  935. # save page
  936. my $file=$page.$config{default_pageext};
  937. my $newfile=1;
  938. if (exists $pagesources{lc($page)}) {
  939. $file=$pagesources{lc($page)};
  940. $newfile=0;
  941. }
  942. my $content=$form->field('content');
  943. $content=~s/\r\n/\n/g;
  944. $content=~s/\r/\n/g;
  945. writefile("$config{srcdir}/$file", $content);
  946. my $message="web commit ";
  947. if ($session->param("name")) {
  948. $message.="by ".$session->param("name");
  949. }
  950. else {
  951. $message.="from $ENV{REMOTE_ADDR}";
  952. }
  953. if (defined $form->field('comments') &&
  954. length $form->field('comments')) {
  955. $message.=": ".$form->field('comments');
  956. }
  957. if ($config{svn}) {
  958. if ($newfile) {
  959. rcs_add($file);
  960. }
  961. # presumably the commit will trigger an update
  962. # of the wiki
  963. rcs_commit($message);
  964. }
  965. else {
  966. loadindex();
  967. refresh();
  968. saveindex();
  969. }
  970. # The trailing question mark tries to avoid broken
  971. # caches and get the most recent version of the page.
  972. print $q->redirect("$config{url}/".htmlpage($page)."?updated");
  973. }
  974. } #}}}
  975. sub cgi () { #{{{
  976. eval q{use CGI};
  977. eval q{use CGI::Session};
  978. my $q=CGI->new;
  979. my $do=$q->param('do');
  980. if (! defined $do || ! length $do) {
  981. error("\"do\" parameter missing");
  982. }
  983. # This does not need a session.
  984. if ($do eq 'recentchanges') {
  985. cgi_recentchanges($q);
  986. return;
  987. }
  988. CGI::Session->name("ikiwiki_session");
  989. my $oldmask=umask(077);
  990. my $session = CGI::Session->new("driver:db_file", $q,
  991. { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
  992. umask($oldmask);
  993. # Everything below this point needs the user to be signed in.
  994. if ((! $config{anonok} && ! defined $session->param("name") ||
  995. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  996. cgi_signin($q, $session);
  997. # Force session flush with safe umask.
  998. my $oldmask=umask(077);
  999. $session->flush;
  1000. umask($oldmask);
  1001. return;
  1002. }
  1003. if ($do eq 'create' || $do eq 'edit') {
  1004. cgi_editpage($q, $session);
  1005. }
  1006. else {
  1007. error("unknown do parameter");
  1008. }
  1009. } #}}}
  1010. sub setup () { # {{{
  1011. my $setup=possibly_foolish_untaint($config{setup});
  1012. delete $config{setup};
  1013. open (IN, $setup) || error("read $setup: $!\n");
  1014. local $/=undef;
  1015. my $code=<IN>;
  1016. ($code)=$code=~/(.*)/s;
  1017. close IN;
  1018. my (%setup);
  1019. eval $code;
  1020. error($@) if $@;
  1021. gen_wrapper(%config, %setup, %{$setup{cgiwrapper}}) if $setup{cgiwrapper};
  1022. gen_wrapper(%config, %setup, %{$setup{svnwrapper}}) if $setup{svnwrapper};
  1023. print "$setup{wikiname} setup complete, now forcing a rebuild\n";
  1024. foreach my $c (keys %setup) {
  1025. $config{$c}=possibly_foolish_untaint($setup{$c})
  1026. if defined $setup{$c} && ! ref $setup{$c};
  1027. }
  1028. $config{rebuild}=1;
  1029. refresh();
  1030. saveindex();
  1031. exit;
  1032. } #}}}
  1033. # main {{{
  1034. setup() if $config{setup};
  1035. if ($config{wrapper}) {
  1036. gen_wrapper(%config);
  1037. exit;
  1038. }
  1039. memoize('pagename');
  1040. memoize('bestlink');
  1041. loadindex() unless $config{rebuild};
  1042. if ($config{cgi}) {
  1043. cgi();
  1044. }
  1045. else {
  1046. rcs_update() if $config{svn};
  1047. refresh();
  1048. saveindex();
  1049. }
  1050. #}}}