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