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