summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: 0f6f250a0f015e0c70e30d60d509b0538900feb1 (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, user => $user,
  381. committype => $committype,
  382. when => $when, message => [@message],
  383. pages => [@pages] } if @pages;
  384. return @ret if @ret >= $num;
  385. $state='header';
  386. $rev=$user=$when=undef;
  387. @pages=@message=();
  388. }
  389. elsif ($state eq 'body') {
  390. push @message, {line => $_},
  391. }
  392. }
  393. }
  394. return @ret;
  395. } #}}}
  396. sub prune ($) { #{{{
  397. my $file=shift;
  398. unlink($file);
  399. my $dir=dirname($file);
  400. while (rmdir($dir)) {
  401. $dir=dirname($dir);
  402. }
  403. } #}}}
  404. sub refresh () { #{{{
  405. # Find existing pages.
  406. my %exists;
  407. my @files;
  408. find({
  409. no_chdir => 1,
  410. wanted => sub {
  411. if (/$wiki_file_prune_regexp/) {
  412. $File::Find::prune=1;
  413. }
  414. elsif (! -d $_) {
  415. my ($f)=/$wiki_file_regexp/; # untaint
  416. if (! defined $f) {
  417. warn("skipping bad filename $_\n");
  418. }
  419. else {
  420. $f=~s/^\Q$srcdir\E\/?//;
  421. push @files, $f;
  422. $exists{pagename($f)}=1;
  423. }
  424. }
  425. },
  426. }, $srcdir);
  427. my %rendered;
  428. # check for added or removed pages
  429. my @add;
  430. foreach my $file (@files) {
  431. my $page=pagename($file);
  432. if (! $oldpagemtime{$page}) {
  433. debug("new page $page");
  434. push @add, $file;
  435. $links{$page}=[];
  436. $pagesources{$page}=$file;
  437. }
  438. }
  439. my @del;
  440. foreach my $page (keys %oldpagemtime) {
  441. if (! $exists{$page}) {
  442. debug("removing old page $page");
  443. push @del, $renderedfiles{$page};
  444. prune($destdir."/".$renderedfiles{$page});
  445. delete $renderedfiles{$page};
  446. $oldpagemtime{$page}=0;
  447. delete $pagesources{$page};
  448. }
  449. }
  450. # render any updated files
  451. foreach my $file (@files) {
  452. my $page=pagename($file);
  453. if (! exists $oldpagemtime{$page} ||
  454. mtime("$srcdir/$file") > $oldpagemtime{$page}) {
  455. debug("rendering changed file $file");
  456. render($file);
  457. $rendered{$file}=1;
  458. }
  459. }
  460. # if any files were added or removed, check to see if each page
  461. # needs an update due to linking to them
  462. # TODO: inefficient; pages may get rendered above and again here;
  463. # problem is the bestlink may have changed and we won't know until
  464. # now
  465. if (@add || @del) {
  466. FILE: foreach my $file (@files) {
  467. my $page=pagename($file);
  468. foreach my $f (@add, @del) {
  469. my $p=pagename($f);
  470. foreach my $link (@{$links{$page}}) {
  471. if (bestlink($page, $link) eq $p) {
  472. debug("rendering $file, which links to $p");
  473. render($file);
  474. $rendered{$file}=1;
  475. next FILE;
  476. }
  477. }
  478. }
  479. }
  480. }
  481. # handle backlinks; if a page has added/removed links, update the
  482. # pages it links to
  483. # TODO: inefficient; pages may get rendered above and again here;
  484. # problem is the backlinks could be wrong in the first pass render
  485. # above
  486. if (%rendered) {
  487. my %linkchanged;
  488. foreach my $file (keys %rendered, @del) {
  489. my $page=pagename($file);
  490. if (exists $links{$page}) {
  491. foreach my $link (@{$links{$page}}) {
  492. $link=bestlink($page, $link);
  493. if (length $link &&
  494. ! exists $oldlinks{$page} ||
  495. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  496. $linkchanged{$link}=1;
  497. }
  498. }
  499. }
  500. if (exists $oldlinks{$page}) {
  501. foreach my $link (@{$oldlinks{$page}}) {
  502. $link=bestlink($page, $link);
  503. if (length $link &&
  504. ! exists $links{$page} ||
  505. ! grep { $_ eq $link } @{$links{$page}}) {
  506. $linkchanged{$link}=1;
  507. }
  508. }
  509. }
  510. }
  511. foreach my $link (keys %linkchanged) {
  512. my $linkfile=$pagesources{$link};
  513. if (defined $linkfile) {
  514. debug("rendering $linkfile, to update its backlinks");
  515. render($linkfile);
  516. }
  517. }
  518. }
  519. } #}}}
  520. # Generates a C wrapper program for running ikiwiki in a specific way.
  521. # The wrapper may be safely made suid.
  522. sub gen_wrapper ($$) { #{{{
  523. my ($svn, $rebuild)=@_;
  524. eval q{use Cwd 'abs_path'};
  525. $srcdir=abs_path($srcdir);
  526. $destdir=abs_path($destdir);
  527. my $this=abs_path($0);
  528. if (! -x $this) {
  529. error("$this doesn't seem to be executable");
  530. }
  531. my @params=($srcdir, $templatedir, $destdir, "--wikiname=$wikiname");
  532. push @params, "--verbose" if $verbose;
  533. push @params, "--rebuild" if $rebuild;
  534. push @params, "--nosvn" if !$svn;
  535. push @params, "--cgi" if $cgi;
  536. push @params, "--url=$url" if $url;
  537. push @params, "--cgiurl=$cgiurl" if $cgiurl;
  538. push @params, "--historyurl=$historyurl" if $historyurl;
  539. push @params, "--anonok" if $anonok;
  540. my $params=join(" ", @params);
  541. my $call='';
  542. foreach my $p ($this, $this, @params) {
  543. $call.=qq{"$p", };
  544. }
  545. $call.="NULL";
  546. my @envsave;
  547. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  548. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  549. HTTP_COOKIE} if $cgi;
  550. my $envsave="";
  551. foreach my $var (@envsave) {
  552. $envsave.=<<"EOF"
  553. if ((s=getenv("$var")))
  554. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  555. EOF
  556. }
  557. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  558. print OUT <<"EOF";
  559. /* A wrapper for ikiwiki, can be safely made suid. */
  560. #define _GNU_SOURCE
  561. #include <stdio.h>
  562. #include <unistd.h>
  563. #include <stdlib.h>
  564. #include <string.h>
  565. extern char **environ;
  566. int main (int argc, char **argv) {
  567. /* Sanitize environment. */
  568. char *s;
  569. char *newenviron[$#envsave+3];
  570. int i=0;
  571. $envsave
  572. newenviron[i++]="HOME=$ENV{HOME}";
  573. newenviron[i]=NULL;
  574. environ=newenviron;
  575. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  576. printf("$params\\n");
  577. exit(0);
  578. }
  579. execl($call);
  580. perror("failed to run $this");
  581. exit(1);
  582. }
  583. EOF
  584. close OUT;
  585. if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
  586. error("failed to compile ikiwiki-wrap.c");
  587. }
  588. unlink("ikiwiki-wrap.c");
  589. print "successfully generated ikiwiki-wrap\n";
  590. exit 0;
  591. } #}}}
  592. sub misctemplate ($$) { #{{{
  593. my $title=shift;
  594. my $pagebody=shift;
  595. my $template=HTML::Template->new(
  596. filename => "$templatedir/misc.tmpl"
  597. );
  598. $template->param(
  599. title => $title,
  600. indexlink => indexlink(),
  601. wikiname => $wikiname,
  602. pagebody => $pagebody,
  603. );
  604. return $template->output;
  605. }#}}}
  606. sub cgi_recentchanges ($) { #{{{
  607. my $q=shift;
  608. my $template=HTML::Template->new(
  609. filename => "$templatedir/recentchanges.tmpl"
  610. );
  611. $template->param(
  612. title => "RecentChanges",
  613. indexlink => indexlink(),
  614. wikiname => $wikiname,
  615. changelog => [rcs_recentchanges(100)],
  616. );
  617. print $q->header, $template->output;
  618. } #}}}
  619. sub userinfo_get ($$) { #{{
  620. my $user=shift;
  621. my $field=shift;
  622. eval q{use Storable};
  623. my $userdata=eval{ Storable::lock_retrieve("$srcdir/.ikiwiki/userdb") };
  624. if (! defined $userdata || ! ref $userdata ||
  625. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  626. return "";
  627. }
  628. return $userdata->{$user}->{$field};
  629. } #}}
  630. sub userinfo_set ($$) { #{{
  631. my $user=shift;
  632. my $info=shift;
  633. eval q{use Storable};
  634. my $userdata=eval{ Storable::lock_retrieve("$srcdir/.ikiwiki/userdb") };
  635. if (! defined $userdata || ! ref $userdata) {
  636. $userdata={};
  637. }
  638. $userdata->{$user}=$info;
  639. my $oldmask=umask(077);
  640. my $ret=Storable::lock_store($userdata, "$srcdir/.ikiwiki/userdb");
  641. umask($oldmask);
  642. return $ret;
  643. } #}}
  644. sub cgi_signin ($$) { #{{{
  645. my $q=shift;
  646. my $session=shift;
  647. eval q{use CGI::FormBuilder};
  648. my $form = CGI::FormBuilder->new(
  649. title => "$wikiname signin",
  650. fields => [qw(do page name password confirm_password email)],
  651. header => 1,
  652. method => 'POST',
  653. validate => {
  654. confirm_password => {
  655. perl => q{eq $form->field("password")},
  656. },
  657. email => 'EMAIL',
  658. },
  659. required => 'NONE',
  660. javascript => 0,
  661. params => $q,
  662. action => $q->request_uri,
  663. header => 0,
  664. template => (-e "$templatedir/signin.tmpl" ? "$templatedir/signin.tmpl" : "")
  665. );
  666. $form->field(name => "name", required => 0);
  667. $form->field(name => "do", type => "hidden");
  668. $form->field(name => "page", type => "hidden");
  669. $form->field(name => "password", type => "password", required => 0);
  670. $form->field(name => "confirm_password", type => "password", required => 0);
  671. $form->field(name => "email", required => 0);
  672. if ($q->param("do") ne "signin") {
  673. $form->text("You need to log in before you can edit pages.");
  674. }
  675. if ($form->submitted) {
  676. # Set required fields based on how form was submitted.
  677. my %required=(
  678. "Login" => [qw(name password)],
  679. "Register" => [qw(name password confirm_password email)],
  680. "Mail Password" => [qw(name)],
  681. );
  682. foreach my $opt (@{$required{$form->submitted}}) {
  683. $form->field(name => $opt, required => 1);
  684. }
  685. # Validate password differently depending on how
  686. # form was submitted.
  687. if ($form->submitted eq 'Login') {
  688. $form->field(
  689. name => "password",
  690. validate => sub {
  691. length $form->field("name") &&
  692. shift eq userinfo_get($form->field("name"), 'password');
  693. },
  694. );
  695. $form->field(name => "name", validate => '/^\w+$/');
  696. }
  697. else {
  698. $form->field(name => "password", validate => 'VALUE');
  699. }
  700. # And make sure the entered name exists when logging
  701. # in or sending email, and does not when registering.
  702. if ($form->submitted eq 'Register') {
  703. $form->field(
  704. name => "name",
  705. validate => sub {
  706. my $name=shift;
  707. length $name &&
  708. ! userinfo_get($name, "regdate");
  709. },
  710. );
  711. }
  712. else {
  713. $form->field(
  714. name => "name",
  715. validate => sub {
  716. my $name=shift;
  717. length $name &&
  718. userinfo_get($name, "regdate");
  719. },
  720. );
  721. }
  722. }
  723. else {
  724. # First time settings.
  725. $form->field(name => "name", comment => "use FirstnameLastName");
  726. $form->field(name => "confirm_password", comment => "(only needed");
  727. $form->field(name => "email", comment => "for registration)");
  728. if ($session->param("name")) {
  729. $form->field(name => "name", value => $session->param("name"));
  730. }
  731. }
  732. if ($form->submitted && $form->validate) {
  733. if ($form->submitted eq 'Login') {
  734. $session->param("name", $form->field("name"));
  735. if (defined $form->field("do") &&
  736. $form->field("do") ne 'signin') {
  737. print $q->redirect(
  738. "$cgiurl?do=".$form->field("do").
  739. "&page=".$form->field("page"));
  740. }
  741. else {
  742. print $q->redirect($url);
  743. }
  744. }
  745. elsif ($form->submitted eq 'Register') {
  746. my $user_name=$form->field('name');
  747. if (userinfo_set($user_name, {
  748. 'email' => $form->field('email'),
  749. 'password' => $form->field('password'),
  750. 'regdate' => time
  751. })) {
  752. $form->field(name => "confirm_password", type => "hidden");
  753. $form->field(name => "email", type => "hidden");
  754. $form->text("Registration successful. Now you can Login.");
  755. print $session->header();
  756. print misctemplate($form->title, $form->render(submit => ["Login"]));
  757. }
  758. else {
  759. error("Error saving registration.");
  760. }
  761. }
  762. elsif ($form->submitted eq 'Mail Password') {
  763. my $user_name=$form->field("name");
  764. my $template=HTML::Template->new(
  765. filename => "$templatedir/passwordmail.tmpl"
  766. );
  767. $template->param(
  768. user_name => $user_name,
  769. user_password => userinfo_get($user_name, "password"),
  770. wikiurl => $url,
  771. wikiname => $wikiname,
  772. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  773. );
  774. eval q{use Mail::Sendmail};
  775. my ($fromhost) = $cgiurl =~ m!/([^/]+)!;
  776. print STDERR "$< $> >>> $cgiurl ".(getpwuid($>))[0]."@".$fromhost."\n";
  777. sendmail(
  778. To => userinfo_get($user_name, "email"),
  779. From => "$wikiname admin <".(getpwuid($>))[0]."@".$fromhost.">",
  780. Subject => "$wikiname information",
  781. Message => $template->output,
  782. ) or error("Failed to send mail");
  783. $form->text("Your password has been emailed to you.");
  784. $form->field(name => "name", required => 0);
  785. print $session->header();
  786. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  787. }
  788. }
  789. else {
  790. print $session->header();
  791. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  792. }
  793. } #}}}
  794. sub cgi_editpage ($$) { #{{{
  795. my $q=shift;
  796. my $session=shift;
  797. eval q{use CGI::FormBuilder};
  798. my $form = CGI::FormBuilder->new(
  799. fields => [qw(do from page content comments)],
  800. header => 1,
  801. method => 'POST',
  802. validate => {},
  803. required => [qw{}],
  804. javascript => 0,
  805. params => $q,
  806. action => $q->request_uri,
  807. table => 0,
  808. template => "$templatedir/editpage.tmpl"
  809. );
  810. my ($page)=$form->param('page')=~/$wiki_file_regexp/;
  811. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  812. $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
  813. error("bad page name");
  814. }
  815. $page=lc($page);
  816. $form->field(name => "do", type => 'hidden');
  817. $form->field(name => "from", type => 'hidden');
  818. $form->field(name => "page", value => "$page", force => 1);
  819. $form->field(name => "comments", type => "text", size => 80);
  820. $form->field(name => "content", type => "textarea", rows => 20,
  821. cols => 80);
  822. if (! $form->submitted || ! $form->validate) {
  823. if ($form->field("do") eq "create") {
  824. if (exists $pagesources{lc($page)}) {
  825. # hmm, someone else made the page in the
  826. # meantime?
  827. print $q->redirect("$url/".htmlpage($page));
  828. return;
  829. }
  830. my @page_locs;
  831. my ($from)=$form->param('from')=~/$wiki_file_regexp/;
  832. if (! defined $from || ! length $from ||
  833. $from ne $form->param('from') ||
  834. $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
  835. @page_locs=$page;
  836. }
  837. else {
  838. my $dir=$from."/";
  839. $dir=~s![^/]+/$!!;
  840. push @page_locs, $dir.$page;
  841. push @page_locs, "$from/$page";
  842. while (length $dir) {
  843. $dir=~s![^/]+/$!!;
  844. push @page_locs, $dir.$page;
  845. }
  846. }
  847. $form->tmpl_param("page_select", 1);
  848. $form->field(name => "page", type => 'select',
  849. options => \@page_locs);
  850. $form->title("creating $page");
  851. }
  852. elsif ($form->field("do") eq "edit") {
  853. my $content="";
  854. if (exists $pagesources{lc($page)}) {
  855. $content=readfile("$srcdir/$pagesources{lc($page)}");
  856. $content=~s/\n/\r\n/g;
  857. }
  858. $form->tmpl_param("page_select", 0);
  859. $form->field(name => "content", value => $content,
  860. force => 1);
  861. $form->field(name => "page", type => 'hidden');
  862. $form->title("editing $page");
  863. }
  864. $form->tmpl_param("can_commit", $svn);
  865. $form->tmpl_param("indexlink", indexlink());
  866. print $form->render(submit => ["Save Page"]);
  867. }
  868. else {
  869. # save page
  870. my $file=$page.$default_pagetype;
  871. my $newfile=1;
  872. if (exists $pagesources{lc($page)}) {
  873. $file=$pagesources{lc($page)};
  874. $newfile=0;
  875. }
  876. my $content=$form->field('content');
  877. $content=~s/\r\n/\n/g;
  878. $content=~s/\r/\n/g;
  879. writefile("$srcdir/$file", $content);
  880. my $message="web commit ";
  881. if ($session->param("name")) {
  882. $message.="by ".$session->param("name");
  883. }
  884. else {
  885. $message.="from $ENV{REMOTE_ADDR}";
  886. }
  887. if (defined $form->field('comments') &&
  888. length $form->field('comments')) {
  889. $message.=": ".$form->field('comments');
  890. }
  891. if ($svn) {
  892. if ($newfile) {
  893. rcs_add($file);
  894. }
  895. # presumably the commit will trigger an update
  896. # of the wiki
  897. rcs_commit($message);
  898. }
  899. else {
  900. refresh();
  901. }
  902. print $q->redirect("$url/".htmlpage($page));
  903. }
  904. } #}}}
  905. sub cgi () { #{{{
  906. eval q{use CGI};
  907. eval q{use CGI::Session};
  908. my $q=CGI->new;
  909. my $do=$q->param('do');
  910. if (! defined $do || ! length $do) {
  911. error("\"do\" parameter missing");
  912. }
  913. # This does not need a session.
  914. if ($do eq 'recentchanges') {
  915. cgi_recentchanges($q);
  916. return;
  917. }
  918. CGI::Session->name("ikiwiki_session");
  919. my $oldmask=umask(077);
  920. my $session = CGI::Session->new("driver:db_file", $q,
  921. { FileName => "$srcdir/.ikiwiki/sessions.db" });
  922. umask($oldmask);
  923. # Everything below this point needs the user to be signed in.
  924. if ((! $anonok && ! defined $session->param("name") ||
  925. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  926. cgi_signin($q, $session);
  927. # Force session flush with safe umask.
  928. my $oldmask=umask(077);
  929. $session->flush;
  930. umask($oldmask);
  931. return;
  932. }
  933. if ($do eq 'create' || $do eq 'edit') {
  934. cgi_editpage($q, $session);
  935. }
  936. else {
  937. error("unknown do parameter");
  938. }
  939. } #}}}
  940. # main {{{
  941. my $rebuild=0;
  942. my $wrapper=0;
  943. if (grep /^-/, @ARGV) {
  944. eval {use Getopt::Long};
  945. GetOptions(
  946. "wikiname=s" => \$wikiname,
  947. "verbose|v" => \$verbose,
  948. "rebuild" => \$rebuild,
  949. "wrapper" => \$wrapper,
  950. "svn!" => \$svn,
  951. "anonok!" => \$anonok,
  952. "cgi" => \$cgi,
  953. "url=s" => \$url,
  954. "cgiurl=s" => \$cgiurl,
  955. "historyurl=s" => \$historyurl,
  956. ) || usage();
  957. }
  958. usage() unless @ARGV == 3;
  959. ($srcdir) = possibly_foolish_untaint(shift);
  960. ($templatedir) = possibly_foolish_untaint(shift);
  961. ($destdir) = possibly_foolish_untaint(shift);
  962. if ($cgi && ! length $url) {
  963. error("Must specify url to wiki with --url when using --cgi");
  964. }
  965. gen_wrapper($svn, $rebuild) if $wrapper;
  966. memoize('pagename');
  967. memoize('bestlink');
  968. loadindex() unless $rebuild;
  969. if ($cgi) {
  970. cgi();
  971. }
  972. else {
  973. rcs_update() if $svn;
  974. refresh();
  975. saveindex();
  976. }
  977. #}}}