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