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