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