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