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