summaryrefslogtreecommitdiff
path: root/ikiwiki
blob: f918980dd49a650a98d314b5ecd20f6e351f370b (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 $page=shift;
  210. $content =~ s{(\\?)$config{wiki_link_regexp}}{
  211. $1 ? "[[$2]]" : htmllink($page, $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, $page);
  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 lockwiki () { #{{{
  336. # Take an exclusive lock on the wiki to prevent multiple concurrent
  337. # run issues. The lock will be dropped on program exit.
  338. if (! -d "$config{srcdir}/.ikiwiki") {
  339. mkdir("$config{srcdir}/.ikiwiki");
  340. }
  341. open(WIKILOCK, ">$config{srcdir}/.ikiwiki/lockfile") || error ("cannot write to lockfile: $!");
  342. if (! flock(WIKILOCK, 2 | 4)) {
  343. debug("wiki seems to be locked, waiting for lock");
  344. my $wait=600; # arbitrary, but don't hang forever to
  345. # prevent process pileup
  346. for (1..600) {
  347. return if flock(WIKILOCK, 2 | 4);
  348. sleep 1;
  349. }
  350. error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
  351. }
  352. } #}}}
  353. sub lockwiki () { #{{{
  354. close WIKILOCK;
  355. } #}}}
  356. sub loadindex () { #{{{
  357. open (IN, "$config{srcdir}/.ikiwiki/index") || return;
  358. while (<IN>) {
  359. $_=possibly_foolish_untaint($_);
  360. chomp;
  361. my ($mtime, $file, $rendered, @links)=split(' ', $_);
  362. my $page=pagename($file);
  363. $pagesources{$page}=$file;
  364. $oldpagemtime{$page}=$mtime;
  365. $oldlinks{$page}=[@links];
  366. $links{$page}=[@links];
  367. $renderedfiles{$page}=$rendered;
  368. }
  369. close IN;
  370. } #}}}
  371. sub saveindex () { #{{{
  372. if (! -d "$config{srcdir}/.ikiwiki") {
  373. mkdir("$config{srcdir}/.ikiwiki");
  374. }
  375. open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
  376. foreach my $page (keys %oldpagemtime) {
  377. print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
  378. join(" ", @{$links{$page}})."\n"
  379. if $oldpagemtime{$page};
  380. }
  381. close OUT;
  382. } #}}}
  383. sub rcs_update () { #{{{
  384. if (-d "$config{srcdir}/.svn") {
  385. if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
  386. warn("svn update failed\n");
  387. }
  388. }
  389. } #}}}
  390. sub rcs_commit ($) { #{{{
  391. my $message=shift;
  392. if (-d "$config{srcdir}/.svn") {
  393. if (system("svn", "commit", "--quiet", "-m",
  394. possibly_foolish_untaint($message),
  395. $config{srcdir}) != 0) {
  396. warn("svn commit failed\n");
  397. }
  398. }
  399. } #}}}
  400. sub rcs_add ($) { #{{{
  401. my $file=shift;
  402. if (-d "$config{srcdir}/.svn") {
  403. my $parent=dirname($file);
  404. while (! -d "$config{srcdir}/$parent/.svn") {
  405. $file=$parent;
  406. $parent=dirname($file);
  407. }
  408. if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
  409. warn("svn add failed\n");
  410. }
  411. }
  412. } #}}}
  413. sub rcs_recentchanges ($) { #{{{
  414. my $num=shift;
  415. my @ret;
  416. eval q{use CGI 'escapeHTML'};
  417. eval q{use Date::Parse};
  418. eval q{use Time::Duration};
  419. if (-d "$config{srcdir}/.svn") {
  420. my $info=`LANG=C svn info $config{srcdir}`;
  421. my ($svn_url)=$info=~/^URL: (.*)$/m;
  422. # FIXME: currently assumes that the wiki is somewhere
  423. # under trunk in svn, doesn't support other layouts.
  424. my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
  425. my $div=qr/^--------------------+$/;
  426. my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
  427. my $state='start';
  428. my ($rev, $user, $when, @pages, @message);
  429. foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
  430. chomp;
  431. if ($state eq 'start' && /$div/) {
  432. $state='header';
  433. }
  434. elsif ($state eq 'header' && /$infoline/) {
  435. $rev=$1;
  436. $user=$2;
  437. $when=concise(ago(time - str2time($3)));
  438. }
  439. elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
  440. push @pages, { link => htmllink("", pagename($1), 1) }
  441. if length $1;
  442. }
  443. elsif ($state eq 'header' && /^$/) {
  444. $state='body';
  445. }
  446. elsif ($state eq 'body' && /$div/) {
  447. my $committype="web";
  448. if (defined $message[0] &&
  449. $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
  450. $user="$1";
  451. $message[0]->{line}=$2;
  452. }
  453. else {
  454. $committype="svn";
  455. }
  456. push @ret, { rev => $rev,
  457. user => htmllink("", $user, 1),
  458. committype => $committype,
  459. when => $when, message => [@message],
  460. pages => [@pages] } if @pages;
  461. return @ret if @ret >= $num;
  462. $state='header';
  463. $rev=$user=$when=undef;
  464. @pages=@message=();
  465. }
  466. elsif ($state eq 'body') {
  467. push @message, {line => escapeHTML($_)},
  468. }
  469. }
  470. }
  471. return @ret;
  472. } #}}}
  473. sub prune ($) { #{{{
  474. my $file=shift;
  475. unlink($file);
  476. my $dir=dirname($file);
  477. while (rmdir($dir)) {
  478. $dir=dirname($dir);
  479. }
  480. } #}}}
  481. sub refresh () { #{{{
  482. # find existing pages
  483. my %exists;
  484. my @files;
  485. eval q{use File::Find};
  486. find({
  487. no_chdir => 1,
  488. wanted => sub {
  489. if (/$config{wiki_file_prune_regexp}/) {
  490. no warnings 'once';
  491. $File::Find::prune=1;
  492. use warnings "all";
  493. }
  494. elsif (! -d $_ && ! -l $_) {
  495. my ($f)=/$config{wiki_file_regexp}/; # untaint
  496. if (! defined $f) {
  497. warn("skipping bad filename $_\n");
  498. }
  499. else {
  500. $f=~s/^\Q$config{srcdir}\E\/?//;
  501. push @files, $f;
  502. $exists{pagename($f)}=1;
  503. }
  504. }
  505. },
  506. }, $config{srcdir});
  507. my %rendered;
  508. # check for added or removed pages
  509. my @add;
  510. foreach my $file (@files) {
  511. my $page=pagename($file);
  512. if (! $oldpagemtime{$page}) {
  513. debug("new page $page");
  514. push @add, $file;
  515. $links{$page}=[];
  516. $pagesources{$page}=$file;
  517. }
  518. }
  519. my @del;
  520. foreach my $page (keys %oldpagemtime) {
  521. if (! $exists{$page}) {
  522. debug("removing old page $page");
  523. push @del, $pagesources{$page};
  524. prune($config{destdir}."/".$renderedfiles{$page});
  525. delete $renderedfiles{$page};
  526. $oldpagemtime{$page}=0;
  527. delete $pagesources{$page};
  528. }
  529. }
  530. # render any updated files
  531. foreach my $file (@files) {
  532. my $page=pagename($file);
  533. if (! exists $oldpagemtime{$page} ||
  534. mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
  535. debug("rendering changed file $file");
  536. render($file);
  537. $rendered{$file}=1;
  538. }
  539. }
  540. # if any files were added or removed, check to see if each page
  541. # needs an update due to linking to them
  542. # TODO: inefficient; pages may get rendered above and again here;
  543. # problem is the bestlink may have changed and we won't know until
  544. # now
  545. if (@add || @del) {
  546. FILE: foreach my $file (@files) {
  547. my $page=pagename($file);
  548. foreach my $f (@add, @del) {
  549. my $p=pagename($f);
  550. foreach my $link (@{$links{$page}}) {
  551. if (bestlink($page, $link) eq $p) {
  552. debug("rendering $file, which links to $p");
  553. render($file);
  554. $rendered{$file}=1;
  555. next FILE;
  556. }
  557. }
  558. }
  559. }
  560. }
  561. # handle backlinks; if a page has added/removed links, update the
  562. # pages it links to
  563. # TODO: inefficient; pages may get rendered above and again here;
  564. # problem is the backlinks could be wrong in the first pass render
  565. # above
  566. if (%rendered) {
  567. my %linkchanged;
  568. foreach my $file (keys %rendered, @del) {
  569. my $page=pagename($file);
  570. if (exists $links{$page}) {
  571. foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
  572. if (length $link &&
  573. ! exists $oldlinks{$page} ||
  574. ! grep { $_ eq $link } @{$oldlinks{$page}}) {
  575. $linkchanged{$link}=1;
  576. }
  577. }
  578. }
  579. if (exists $oldlinks{$page}) {
  580. foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
  581. if (length $link &&
  582. ! exists $links{$page} ||
  583. ! grep { $_ eq $link } @{$links{$page}}) {
  584. $linkchanged{$link}=1;
  585. }
  586. }
  587. }
  588. }
  589. foreach my $link (keys %linkchanged) {
  590. my $linkfile=$pagesources{$link};
  591. if (defined $linkfile) {
  592. debug("rendering $linkfile, to update its backlinks");
  593. render($linkfile);
  594. }
  595. }
  596. }
  597. } #}}}
  598. sub gen_wrapper (@) { #{{{
  599. my %config=(@_);
  600. eval q{use Cwd 'abs_path'};
  601. $config{srcdir}=abs_path($config{srcdir});
  602. $config{destdir}=abs_path($config{destdir});
  603. my $this=abs_path($0);
  604. if (! -x $this) {
  605. error("$this doesn't seem to be executable");
  606. }
  607. if ($config{setup}) {
  608. error("cannot create a wrapper that uses a setup file");
  609. }
  610. my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
  611. "--wikiname=$config{wikiname}");
  612. push @params, "--verbose" if $config{verbose};
  613. push @params, "--rebuild" if $config{rebuild};
  614. push @params, "--nosvn" if !$config{svn};
  615. push @params, "--cgi" if $config{cgi};
  616. push @params, "--url=$config{url}" if length $config{url};
  617. push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
  618. push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
  619. push @params, "--anonok" if $config{anonok};
  620. my $params=join(" ", @params);
  621. my $call='';
  622. foreach my $p ($this, $this, @params) {
  623. $call.=qq{"$p", };
  624. }
  625. $call.="NULL";
  626. my @envsave;
  627. push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
  628. CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
  629. HTTP_COOKIE} if $config{cgi};
  630. my $envsave="";
  631. foreach my $var (@envsave) {
  632. $envsave.=<<"EOF"
  633. if ((s=getenv("$var")))
  634. asprintf(&newenviron[i++], "%s=%s", "$var", s);
  635. EOF
  636. }
  637. open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
  638. print OUT <<"EOF";
  639. /* A wrapper for ikiwiki, can be safely made suid. */
  640. #define _GNU_SOURCE
  641. #include <stdio.h>
  642. #include <unistd.h>
  643. #include <stdlib.h>
  644. #include <string.h>
  645. extern char **environ;
  646. int main (int argc, char **argv) {
  647. /* Sanitize environment. */
  648. char *s;
  649. char *newenviron[$#envsave+3];
  650. int i=0;
  651. $envsave
  652. newenviron[i++]="HOME=$ENV{HOME}";
  653. newenviron[i]=NULL;
  654. environ=newenviron;
  655. if (argc == 2 && strcmp(argv[1], "--params") == 0) {
  656. printf("$params\\n");
  657. exit(0);
  658. }
  659. execl($call);
  660. perror("failed to run $this");
  661. exit(1);
  662. }
  663. EOF
  664. close OUT;
  665. if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
  666. error("failed to compile ikiwiki-wrap.c");
  667. }
  668. unlink("ikiwiki-wrap.c");
  669. if (defined $config{wrappermode} &&
  670. ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
  671. error("chmod $config{wrapper}: $!");
  672. }
  673. print "successfully generated $config{wrapper}\n";
  674. } #}}}
  675. sub misctemplate ($$) { #{{{
  676. my $title=shift;
  677. my $pagebody=shift;
  678. my $template=HTML::Template->new(
  679. filename => "$config{templatedir}/misc.tmpl"
  680. );
  681. $template->param(
  682. title => $title,
  683. indexlink => indexlink(),
  684. wikiname => $config{wikiname},
  685. pagebody => $pagebody,
  686. );
  687. return $template->output;
  688. }#}}}
  689. sub cgi_recentchanges ($) { #{{{
  690. my $q=shift;
  691. my $template=HTML::Template->new(
  692. filename => "$config{templatedir}/recentchanges.tmpl"
  693. );
  694. $template->param(
  695. title => "RecentChanges",
  696. indexlink => indexlink(),
  697. wikiname => $config{wikiname},
  698. changelog => [rcs_recentchanges(100)],
  699. );
  700. print $q->header, $template->output;
  701. } #}}}
  702. sub userinfo_get ($$) { #{{{
  703. my $user=shift;
  704. my $field=shift;
  705. eval q{use Storable};
  706. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  707. if (! defined $userdata || ! ref $userdata ||
  708. ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
  709. return "";
  710. }
  711. return $userdata->{$user}->{$field};
  712. } #}}}
  713. sub userinfo_set ($$) { #{{{
  714. my $user=shift;
  715. my $info=shift;
  716. eval q{use Storable};
  717. my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
  718. if (! defined $userdata || ! ref $userdata) {
  719. $userdata={};
  720. }
  721. $userdata->{$user}=$info;
  722. my $oldmask=umask(077);
  723. my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
  724. umask($oldmask);
  725. return $ret;
  726. } #}}}
  727. sub cgi_signin ($$) { #{{{
  728. my $q=shift;
  729. my $session=shift;
  730. eval q{use CGI::FormBuilder};
  731. my $form = CGI::FormBuilder->new(
  732. title => "$config{wikiname} signin",
  733. fields => [qw(do page from name password confirm_password email)],
  734. header => 1,
  735. method => 'POST',
  736. validate => {
  737. confirm_password => {
  738. perl => q{eq $form->field("password")},
  739. },
  740. email => 'EMAIL',
  741. },
  742. required => 'NONE',
  743. javascript => 0,
  744. params => $q,
  745. action => $q->request_uri,
  746. header => 0,
  747. template => (-e "$config{templatedir}/signin.tmpl" ?
  748. "$config{templatedir}/signin.tmpl" : "")
  749. );
  750. $form->field(name => "name", required => 0);
  751. $form->field(name => "do", type => "hidden");
  752. $form->field(name => "page", type => "hidden");
  753. $form->field(name => "from", type => "hidden");
  754. $form->field(name => "password", type => "password", required => 0);
  755. $form->field(name => "confirm_password", type => "password", required => 0);
  756. $form->field(name => "email", required => 0);
  757. if ($q->param("do") ne "signin") {
  758. $form->text("You need to log in before you can edit pages.");
  759. }
  760. if ($form->submitted) {
  761. # Set required fields based on how form was submitted.
  762. my %required=(
  763. "Login" => [qw(name password)],
  764. "Register" => [qw(name password confirm_password email)],
  765. "Mail Password" => [qw(name)],
  766. );
  767. foreach my $opt (@{$required{$form->submitted}}) {
  768. $form->field(name => $opt, required => 1);
  769. }
  770. # Validate password differently depending on how
  771. # form was submitted.
  772. if ($form->submitted eq 'Login') {
  773. $form->field(
  774. name => "password",
  775. validate => sub {
  776. length $form->field("name") &&
  777. shift eq userinfo_get($form->field("name"), 'password');
  778. },
  779. );
  780. $form->field(name => "name", validate => '/^\w+$/');
  781. }
  782. else {
  783. $form->field(name => "password", validate => 'VALUE');
  784. }
  785. # And make sure the entered name exists when logging
  786. # in or sending email, and does not when registering.
  787. if ($form->submitted eq 'Register') {
  788. $form->field(
  789. name => "name",
  790. validate => sub {
  791. my $name=shift;
  792. length $name &&
  793. ! userinfo_get($name, "regdate");
  794. },
  795. );
  796. }
  797. else {
  798. $form->field(
  799. name => "name",
  800. validate => sub {
  801. my $name=shift;
  802. length $name &&
  803. userinfo_get($name, "regdate");
  804. },
  805. );
  806. }
  807. }
  808. else {
  809. # First time settings.
  810. $form->field(name => "name", comment => "use FirstnameLastName");
  811. $form->field(name => "confirm_password", comment => "(only needed");
  812. $form->field(name => "email", comment => "for registration)");
  813. if ($session->param("name")) {
  814. $form->field(name => "name", value => $session->param("name"));
  815. }
  816. }
  817. if ($form->submitted && $form->validate) {
  818. if ($form->submitted eq 'Login') {
  819. $session->param("name", $form->field("name"));
  820. if (defined $form->field("do") &&
  821. $form->field("do") ne 'signin') {
  822. print $q->redirect(
  823. "$config{cgiurl}?do=".$form->field("do").
  824. "&page=".$form->field("page").
  825. "&from=".$form->field("from"));;
  826. }
  827. else {
  828. print $q->redirect($config{url});
  829. }
  830. }
  831. elsif ($form->submitted eq 'Register') {
  832. my $user_name=$form->field('name');
  833. if (userinfo_set($user_name, {
  834. 'email' => $form->field('email'),
  835. 'password' => $form->field('password'),
  836. 'regdate' => time
  837. })) {
  838. $form->field(name => "confirm_password", type => "hidden");
  839. $form->field(name => "email", type => "hidden");
  840. $form->text("Registration successful. Now you can Login.");
  841. print $session->header();
  842. print misctemplate($form->title, $form->render(submit => ["Login"]));
  843. }
  844. else {
  845. error("Error saving registration.");
  846. }
  847. }
  848. elsif ($form->submitted eq 'Mail Password') {
  849. my $user_name=$form->field("name");
  850. my $template=HTML::Template->new(
  851. filename => "$config{templatedir}/passwordmail.tmpl"
  852. );
  853. $template->param(
  854. user_name => $user_name,
  855. user_password => userinfo_get($user_name, "password"),
  856. wikiurl => $config{url},
  857. wikiname => $config{wikiname},
  858. REMOTE_ADDR => $ENV{REMOTE_ADDR},
  859. );
  860. eval q{use Mail::Sendmail};
  861. my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
  862. sendmail(
  863. To => userinfo_get($user_name, "email"),
  864. From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
  865. Subject => "$config{wikiname} information",
  866. Message => $template->output,
  867. ) or error("Failed to send mail");
  868. $form->text("Your password has been emailed to you.");
  869. $form->field(name => "name", required => 0);
  870. print $session->header();
  871. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  872. }
  873. }
  874. else {
  875. print $session->header();
  876. print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
  877. }
  878. } #}}}
  879. sub cgi_editpage ($$) { #{{{
  880. my $q=shift;
  881. my $session=shift;
  882. eval q{use CGI::FormBuilder};
  883. my $form = CGI::FormBuilder->new(
  884. fields => [qw(do from page content comments)],
  885. header => 1,
  886. method => 'POST',
  887. validate => {
  888. content => '/.+/',
  889. },
  890. required => [qw{content}],
  891. javascript => 0,
  892. params => $q,
  893. action => $q->request_uri,
  894. table => 0,
  895. template => "$config{templatedir}/editpage.tmpl"
  896. );
  897. my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
  898. if (! defined $page || ! length $page || $page ne $q->param('page') ||
  899. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  900. error("bad page name");
  901. }
  902. $page=lc($page);
  903. $form->field(name => "do", type => 'hidden');
  904. $form->field(name => "from", type => 'hidden');
  905. $form->field(name => "page", value => "$page", force => 1);
  906. $form->field(name => "comments", type => "text", size => 80);
  907. $form->field(name => "content", type => "textarea", rows => 20,
  908. cols => 80);
  909. if ($form->submitted eq "Cancel") {
  910. print $q->redirect("$config{url}/".htmlpage($page));
  911. return;
  912. }
  913. elsif ($form->submitted eq "Preview") {
  914. $form->tmpl_param("page_preview",
  915. htmlize($config{default_pageext},
  916. linkify($form->field('content'), $page)));
  917. }
  918. else {
  919. $form->tmpl_param("page_preview", "");
  920. }
  921. if (! $form->submitted || $form->submitted eq "Preview" ||
  922. ! $form->validate) {
  923. if ($form->field("do") eq "create") {
  924. if (exists $pagesources{lc($page)}) {
  925. # hmm, someone else made the page in the
  926. # meantime?
  927. print $q->redirect("$config{url}/".htmlpage($page));
  928. return;
  929. }
  930. my @page_locs;
  931. my $best_loc;
  932. my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
  933. if (! defined $from || ! length $from ||
  934. $from ne $form->param('from') ||
  935. $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
  936. @page_locs=$best_loc=$page;
  937. }
  938. else {
  939. my $dir=$from."/";
  940. $dir=~s![^/]+/$!!;
  941. push @page_locs, $dir.$page;
  942. push @page_locs, "$from/$page";
  943. $best_loc="$from/$page";
  944. while (length $dir) {
  945. $dir=~s![^/]+/$!!;
  946. push @page_locs, $dir.$page;
  947. }
  948. @page_locs = grep { ! exists
  949. $pagesources{lc($_)} } @page_locs;
  950. }
  951. $form->tmpl_param("page_select", 1);
  952. $form->field(name => "page", type => 'select',
  953. options => \@page_locs, value => $best_loc);
  954. $form->title("creating $page");
  955. }
  956. elsif ($form->field("do") eq "edit") {
  957. if (! length $form->field('content')) {
  958. my $content="";
  959. if (exists $pagesources{lc($page)}) {
  960. $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
  961. $content=~s/\n/\r\n/g;
  962. }
  963. $form->field(name => "content", value => $content,
  964. force => 1);
  965. }
  966. $form->tmpl_param("page_select", 0);
  967. $form->field(name => "page", type => 'hidden');
  968. $form->title("editing $page");
  969. }
  970. $form->tmpl_param("can_commit", $config{svn});
  971. $form->tmpl_param("indexlink", indexlink());
  972. print $form->render(submit => ["Save Page", "Preview", "Cancel"]);
  973. }
  974. else {
  975. # save page
  976. my $file=$page.$config{default_pageext};
  977. my $newfile=1;
  978. if (exists $pagesources{lc($page)}) {
  979. $file=$pagesources{lc($page)};
  980. $newfile=0;
  981. }
  982. my $content=$form->field('content');
  983. $content=~s/\r\n/\n/g;
  984. $content=~s/\r/\n/g;
  985. writefile("$config{srcdir}/$file", $content);
  986. my $message="web commit ";
  987. if ($session->param("name")) {
  988. $message.="by ".$session->param("name");
  989. }
  990. else {
  991. $message.="from $ENV{REMOTE_ADDR}";
  992. }
  993. if (defined $form->field('comments') &&
  994. length $form->field('comments')) {
  995. $message.=": ".$form->field('comments');
  996. }
  997. if ($config{svn}) {
  998. if ($newfile) {
  999. rcs_add($file);
  1000. }
  1001. # presumably the commit will trigger an update
  1002. # of the wiki
  1003. rcs_commit($message);
  1004. unlock_wiki();
  1005. }
  1006. else {
  1007. loadindex();
  1008. refresh();
  1009. saveindex();
  1010. }
  1011. # The trailing question mark tries to avoid broken
  1012. # caches and get the most recent version of the page.
  1013. print $q->redirect("$config{url}/".htmlpage($page)."?updated");
  1014. }
  1015. } #}}}
  1016. sub cgi () { #{{{
  1017. eval q{use CGI};
  1018. eval q{use CGI::Session};
  1019. my $q=CGI->new;
  1020. my $do=$q->param('do');
  1021. if (! defined $do || ! length $do) {
  1022. error("\"do\" parameter missing");
  1023. }
  1024. # This does not need a session.
  1025. if ($do eq 'recentchanges') {
  1026. cgi_recentchanges($q);
  1027. return;
  1028. }
  1029. CGI::Session->name("ikiwiki_session");
  1030. my $oldmask=umask(077);
  1031. my $session = CGI::Session->new("driver:db_file", $q,
  1032. { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
  1033. umask($oldmask);
  1034. # Everything below this point needs the user to be signed in.
  1035. if ((! $config{anonok} && ! defined $session->param("name") ||
  1036. ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
  1037. cgi_signin($q, $session);
  1038. # Force session flush with safe umask.
  1039. my $oldmask=umask(077);
  1040. $session->flush;
  1041. umask($oldmask);
  1042. return;
  1043. }
  1044. if ($do eq 'create' || $do eq 'edit') {
  1045. cgi_editpage($q, $session);
  1046. }
  1047. else {
  1048. error("unknown do parameter");
  1049. }
  1050. } #}}}
  1051. sub setup () { # {{{
  1052. my $setup=possibly_foolish_untaint($config{setup});
  1053. delete $config{setup};
  1054. open (IN, $setup) || error("read $setup: $!\n");
  1055. local $/=undef;
  1056. my $code=<IN>;
  1057. ($code)=$code=~/(.*)/s;
  1058. close IN;
  1059. eval $code;
  1060. error($@) if $@;
  1061. exit;
  1062. } #}}}
  1063. # main {{{
  1064. lockwiki();
  1065. setup() if $config{setup};
  1066. if ($config{wrapper}) {
  1067. gen_wrapper(%config);
  1068. exit;
  1069. }
  1070. memoize('pagename');
  1071. memoize('bestlink');
  1072. loadindex() unless $config{rebuild};
  1073. if ($config{cgi}) {
  1074. cgi();
  1075. }
  1076. else {
  1077. rcs_update() if $config{svn};
  1078. refresh();
  1079. saveindex();
  1080. }
  1081. #}}}