summaryrefslogtreecommitdiff
path: root/IkiWiki/CGI.pm
blob: 1caea99a4e6d930705154830c2271c9fcebf11ee (plain)
  1. #!/usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use IkiWiki;
  5. use IkiWiki::UserInfo;
  6. use open qw{:utf8 :std};
  7. use Encode;
  8. package IkiWiki;
  9. sub printheader ($) { #{{{
  10. my $session=shift;
  11. if ($config{sslcookie}) {
  12. print $session->header(-charset => 'utf-8',
  13. -cookie => $session->cookie(-secure => 1));
  14. } else {
  15. print $session->header(-charset => 'utf-8');
  16. }
  17. } #}}}
  18. sub redirect ($$) { #{{{
  19. my $q=shift;
  20. my $url=shift;
  21. if (! $config{w3mmode}) {
  22. print $q->redirect($url);
  23. }
  24. else {
  25. print "Content-type: text/plain\n";
  26. print "W3m-control: GOTO $url\n\n";
  27. }
  28. } #}}}
  29. sub page_locked ($$;$) { #{{{
  30. my $page=shift;
  31. my $session=shift;
  32. my $nonfatal=shift;
  33. my $user=$session->param("name");
  34. return if defined $user && is_admin($user);
  35. foreach my $admin (@{$config{adminuser}}) {
  36. my $locked_pages=userinfo_get($admin, "locked_pages");
  37. if (pagespec_match($page, userinfo_get($admin, "locked_pages"))) {
  38. return 1 if $nonfatal;
  39. error(htmllink("", "", $page, 1)." is locked by ".
  40. userlink($admin)." and cannot be edited.");
  41. }
  42. }
  43. return 0;
  44. } #}}}
  45. sub decode_form_utf8 ($) { #{{{
  46. my $form = shift;
  47. foreach my $f ($form->field) {
  48. next if Encode::is_utf8(scalar $form->field($f));
  49. $form->field(name => $f,
  50. value => decode_utf8($form->field($f)),
  51. force => 1,
  52. );
  53. }
  54. } #}}}
  55. sub cgi_recentchanges ($) { #{{{
  56. my $q=shift;
  57. # Optimisation: building recentchanges means calculating lots of
  58. # links. Memoizing htmllink speeds it up a lot (can't be memoized
  59. # during page builds as the return values may change, but they
  60. # won't here.)
  61. eval q{use Memoize};
  62. error($@) if $@;
  63. memoize("htmllink");
  64. eval q{use Time::Duration};
  65. error($@) if $@;
  66. my $changelog=[rcs_recentchanges(100)];
  67. foreach my $change (@$changelog) {
  68. $change->{when} = concise(ago($change->{when}));
  69. $change->{user} = userlink($change->{user});
  70. my $is_excess = exists $change->{pages}[10]; # limit pages to first 10
  71. delete @{$change->{pages}}[10 .. @{$change->{pages}}] if $is_excess;
  72. $change->{pages} = [
  73. map {
  74. $_->{link} = htmllink("", "", $_->{page}, 1);
  75. $_;
  76. } @{$change->{pages}}
  77. ];
  78. push @{$change->{pages}}, { link => '...' } if $is_excess;
  79. }
  80. my $template=template("recentchanges.tmpl");
  81. $template->param(
  82. title => "RecentChanges",
  83. indexlink => indexlink(),
  84. wikiname => $config{wikiname},
  85. changelog => $changelog,
  86. baseurl => baseurl(),
  87. );
  88. run_hooks(pagetemplate => sub {
  89. shift->(page => "", destpage => "", template => $template);
  90. });
  91. print $q->header(-charset => 'utf-8'), $template->output;
  92. } #}}}
  93. sub cgi_signin ($$) { #{{{
  94. my $q=shift;
  95. my $session=shift;
  96. eval q{use CGI::FormBuilder};
  97. error($@) if $@;
  98. my $form = CGI::FormBuilder->new(
  99. title => "signin",
  100. header => 1,
  101. charset => "utf-8",
  102. method => 'POST',
  103. required => 'NONE',
  104. javascript => 0,
  105. params => $q,
  106. action => $config{cgiurl},
  107. header => 0,
  108. template => (-e "$config{templatedir}/signin.tmpl" ?
  109. {template_params("signin.tmpl")} : ""),
  110. stylesheet => baseurl()."style.css",
  111. );
  112. my $buttons=["Login"];
  113. $form->field(name => "do", type => "hidden");
  114. if ($q->param("do") ne "signin" && !$form->submitted) {
  115. $form->text("You need to log in first.");
  116. }
  117. run_hooks(formbuilder_setup => sub {
  118. shift->(form => $form, cgi => $q, session => $session);
  119. });
  120. decode_form_utf8($form);
  121. if (exists $hooks{formbuilder}) {
  122. run_hooks(formbuilder => sub {
  123. shift->(form => $form, cgi => $q, session => $session,
  124. buttons => $buttons);
  125. });
  126. }
  127. else {
  128. if ($form->submitted) {
  129. $form->validate;
  130. }
  131. printheader($session);
  132. print misctemplate($form->title, $form->render(submit => $buttons));
  133. }
  134. } #}}}
  135. sub cgi_postsignin ($$) { #{{{
  136. my $q=shift;
  137. my $session=shift;
  138. # Continue with whatever was being done before the signin process.
  139. if (defined $q->param("do") && $q->param("do") ne "signin" &&
  140. defined $session->param("postsignin")) {
  141. my $postsignin=CGI->new($session->param("postsignin"));
  142. $session->clear("postsignin");
  143. cgi($postsignin, $session);
  144. exit;
  145. }
  146. else {
  147. redirect($q, $config{url});
  148. }
  149. } #}}}
  150. sub cgi_prefs ($$) { #{{{
  151. my $q=shift;
  152. my $session=shift;
  153. eval q{use CGI::FormBuilder};
  154. error($@) if $@;
  155. my $form = CGI::FormBuilder->new(
  156. title => "preferences",
  157. header => 0,
  158. charset => "utf-8",
  159. method => 'POST',
  160. validate => {
  161. email => 'EMAIL',
  162. },
  163. required => 'NONE',
  164. javascript => 0,
  165. params => $q,
  166. action => $config{cgiurl},
  167. template => (-e "$config{templatedir}/prefs.tmpl" ?
  168. {template_params("prefs.tmpl")} : ""),
  169. stylesheet => baseurl()."style.css",
  170. );
  171. my $buttons=["Save Preferences", "Logout", "Cancel"];
  172. run_hooks(formbuilder_setup => sub {
  173. shift->(form => $form, cgi => $q, session => $session);
  174. });
  175. $form->field(name => "do", type => "hidden");
  176. $form->field(name => "email", size => 50);
  177. $form->field(name => "subscriptions", size => 50,
  178. comment => "(".htmllink("", "", "PageSpec", 1).")");
  179. $form->field(name => "locked_pages", size => 50,
  180. comment => "(".htmllink("", "", "PageSpec", 1).")");
  181. $form->field(name => "banned_users", size => 50);
  182. my $user_name=$session->param("name");
  183. if (! is_admin($user_name)) {
  184. $form->field(name => "locked_pages", type => "hidden");
  185. $form->field(name => "banned_users", type => "hidden");
  186. }
  187. if (! $form->submitted) {
  188. $form->field(name => "email", force => 1,
  189. value => userinfo_get($user_name, "email"));
  190. $form->field(name => "subscriptions", force => 1,
  191. value => userinfo_get($user_name, "subscriptions"));
  192. $form->field(name => "locked_pages", force => 1,
  193. value => userinfo_get($user_name, "locked_pages"));
  194. if (is_admin($user_name)) {
  195. $form->field(name => "banned_users", force => 1,
  196. value => join(" ", get_banned_users()));
  197. }
  198. }
  199. decode_form_utf8($form);
  200. if ($form->submitted eq 'Logout') {
  201. $session->delete();
  202. redirect($q, $config{url});
  203. return;
  204. }
  205. elsif ($form->submitted eq 'Cancel') {
  206. redirect($q, $config{url});
  207. return;
  208. }
  209. elsif ($form->submitted eq "Save Preferences" && $form->validate) {
  210. foreach my $field (qw(email subscriptions locked_pages)) {
  211. if (defined $form->field($field) && length $form->field($field)) {
  212. userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
  213. }
  214. }
  215. if (is_admin($user_name)) {
  216. set_banned_users(grep { ! is_admin($_) }
  217. split(' ', $form->field("banned_users")));
  218. }
  219. $form->text("Preferences saved.");
  220. }
  221. if (exists $hooks{formbuilder}) {
  222. run_hooks(formbuilder => sub {
  223. shift->(form => $form, cgi => $q, session => $session,
  224. buttons => $buttons);
  225. });
  226. }
  227. else {
  228. printheader($session);
  229. print misctemplate($form->title, $form->render(submit => $buttons));
  230. }
  231. } #}}}
  232. sub cgi_editpage ($$) { #{{{
  233. my $q=shift;
  234. my $session=shift;
  235. my @fields=qw(do rcsinfo subpage from page type editcontent comments);
  236. my @buttons=("Save Page", "Preview", "Cancel");
  237. eval q{use CGI::FormBuilder; use CGI::FormBuilder::Template::HTML};
  238. error($@) if $@;
  239. my $renderer=CGI::FormBuilder::Template::HTML->new(
  240. fields => \@fields,
  241. template_params("editpage.tmpl"),
  242. );
  243. run_hooks(pagetemplate => sub {
  244. shift->(page => "", destpage => "", template => $renderer->engine);
  245. });
  246. my $form = CGI::FormBuilder->new(
  247. fields => \@fields,
  248. header => 1,
  249. charset => "utf-8",
  250. method => 'POST',
  251. validate => {
  252. editcontent => '/.+/',
  253. },
  254. required => [qw{editcontent}],
  255. javascript => 0,
  256. params => $q,
  257. action => $config{cgiurl},
  258. table => 0,
  259. template => $renderer,
  260. );
  261. run_hooks(formbuilder_setup => sub {
  262. shift->(form => $form, cgi => $q, session => $session);
  263. });
  264. decode_form_utf8($form);
  265. # This untaint is safe because titlepage removes any problematic
  266. # characters.
  267. my ($page)=$form->field('page');
  268. $page=titlepage(possibly_foolish_untaint($page));
  269. if (! defined $page || ! length $page ||
  270. $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
  271. error("bad page name");
  272. }
  273. my $from;
  274. if (defined $form->field('from')) {
  275. ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
  276. }
  277. my $file;
  278. my $type;
  279. if (exists $pagesources{$page}) {
  280. $file=$pagesources{$page};
  281. $type=pagetype($file);
  282. }
  283. else {
  284. $type=$form->param('type');
  285. if (defined $type && length $type && $hooks{htmlize}{$type}) {
  286. $type=possibly_foolish_untaint($type);
  287. }
  288. elsif (defined $from) {
  289. # favor the type of linking page
  290. $type=pagetype($pagesources{$from});
  291. }
  292. $type=$config{default_pageext} unless defined $type;
  293. $file=$page.".".$type;
  294. }
  295. my $newfile=0;
  296. if (! -e "$config{srcdir}/$file") {
  297. $newfile=1;
  298. }
  299. $form->field(name => "do", type => 'hidden');
  300. $form->field(name => "from", type => 'hidden');
  301. $form->field(name => "rcsinfo", type => 'hidden');
  302. $form->field(name => "subpage", type => 'hidden');
  303. $form->field(name => "page", value => $page, force => 1);
  304. $form->field(name => "type", value => $type, force => 1);
  305. $form->field(name => "comments", type => "text", size => 80);
  306. $form->field(name => "editcontent", type => "textarea", rows => 20,
  307. cols => 80);
  308. $form->tmpl_param("can_commit", $config{rcs});
  309. $form->tmpl_param("indexlink", indexlink());
  310. $form->tmpl_param("helponformattinglink",
  311. htmllink("", "", "HelpOnFormatting", 1));
  312. $form->tmpl_param("baseurl", baseurl());
  313. if (! $form->submitted) {
  314. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  315. force => 1);
  316. }
  317. if ($form->submitted eq "Cancel") {
  318. if ($newfile && defined $from) {
  319. redirect($q, "$config{url}/".htmlpage($from));
  320. }
  321. elsif ($newfile) {
  322. redirect($q, $config{url});
  323. }
  324. else {
  325. redirect($q, "$config{url}/".htmlpage($page));
  326. }
  327. return;
  328. }
  329. elsif ($form->submitted eq "Preview") {
  330. my $content=$form->field('editcontent');
  331. my $comments=$form->field('comments');
  332. $form->field(name => "editcontent",
  333. value => $content, force => 1);
  334. $form->field(name => "comments",
  335. value => $comments, force => 1);
  336. $config{rss}=$config{atom}=0; # avoid preview writing a feed!
  337. $form->tmpl_param("page_preview",
  338. htmlize($page, $type,
  339. linkify($page, "",
  340. preprocess($page, $page,
  341. filter($page, $content)))));
  342. }
  343. else {
  344. $form->tmpl_param("page_preview", "");
  345. }
  346. $form->tmpl_param("page_conflict", "");
  347. if (! $form->submitted || $form->submitted eq "Preview" ||
  348. ! $form->validate) {
  349. if ($form->field("do") eq "create") {
  350. my @page_locs;
  351. my $best_loc;
  352. if (! defined $from || ! length $from ||
  353. $from ne $form->field('from') ||
  354. $from=~/$config{wiki_file_prune_regexp}/ ||
  355. $from=~/^\// ||
  356. $form->submitted eq "Preview") {
  357. @page_locs=$best_loc=$page;
  358. }
  359. else {
  360. my $dir=$from."/";
  361. $dir=~s![^/]+/+$!!;
  362. if ((defined $form->field('subpage') && length $form->field('subpage')) ||
  363. $page eq 'discussion') {
  364. $best_loc="$from/$page";
  365. }
  366. else {
  367. $best_loc=$dir.$page;
  368. }
  369. push @page_locs, $dir.$page;
  370. push @page_locs, "$from/$page";
  371. while (length $dir) {
  372. $dir=~s![^/]+/+$!!;
  373. push @page_locs, $dir.$page;
  374. }
  375. }
  376. @page_locs = grep {
  377. ! exists $pagecase{lc $_} &&
  378. ! page_locked($_, $session, 1)
  379. } @page_locs;
  380. if (! @page_locs) {
  381. # hmm, someone else made the page in the
  382. # meantime?
  383. redirect($q, "$config{url}/".htmlpage($page));
  384. return;
  385. }
  386. my @page_types;
  387. if (exists $hooks{htmlize}) {
  388. @page_types=keys %{$hooks{htmlize}};
  389. }
  390. $form->tmpl_param("page_select", 1);
  391. $form->field(name => "page", type => 'select',
  392. options => \@page_locs, value => $best_loc);
  393. $form->field(name => "type", type => 'select',
  394. options => \@page_types);
  395. $form->title("creating ".pagetitle($page));
  396. }
  397. elsif ($form->field("do") eq "edit") {
  398. page_locked($page, $session);
  399. if (! defined $form->field('editcontent') ||
  400. ! length $form->field('editcontent')) {
  401. my $content="";
  402. if (exists $pagesources{$page}) {
  403. $content=readfile(srcfile($pagesources{$page}));
  404. $content=~s/\n/\r\n/g;
  405. }
  406. $form->field(name => "editcontent", value => $content,
  407. force => 1);
  408. }
  409. $form->tmpl_param("page_select", 0);
  410. $form->field(name => "page", type => 'hidden');
  411. $form->field(name => "type", type => 'hidden');
  412. $form->title("editing ".pagetitle($page));
  413. }
  414. print $form->render(submit => \@buttons);
  415. }
  416. else {
  417. # save page
  418. page_locked($page, $session);
  419. my $content=$form->field('editcontent');
  420. $content=~s/\r\n/\n/g;
  421. $content=~s/\r/\n/g;
  422. writefile($file, $config{srcdir}, $content);
  423. if ($config{rcs}) {
  424. my $message="";
  425. if (defined $form->field('comments') &&
  426. length $form->field('comments')) {
  427. $message=$form->field('comments');
  428. }
  429. if ($newfile) {
  430. rcs_add($file);
  431. }
  432. # prevent deadlock with post-commit hook
  433. unlockwiki();
  434. # presumably the commit will trigger an update
  435. # of the wiki
  436. my $conflict=rcs_commit($file, $message,
  437. $form->field("rcsinfo"),
  438. $session->param("name"), $ENV{REMOTE_ADDR});
  439. if (defined $conflict) {
  440. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  441. force => 1);
  442. $form->tmpl_param("page_conflict", 1);
  443. $form->field("editcontent", value => $conflict, force => 1);
  444. $form->field(name => "comments", value => $form->field('comments'), force => 1);
  445. $form->field("do", "edit)");
  446. $form->tmpl_param("page_select", 0);
  447. $form->field(name => "page", type => 'hidden');
  448. $form->field(name => "type", type => 'hidden');
  449. $form->title("editing $page");
  450. print $form->render(submit => \@buttons);
  451. return;
  452. }
  453. }
  454. else {
  455. require IkiWiki::Render;
  456. refresh();
  457. saveindex();
  458. }
  459. # The trailing question mark tries to avoid broken
  460. # caches and get the most recent version of the page.
  461. redirect($q, "$config{url}/".htmlpage($page)."?updated");
  462. }
  463. } #}}}
  464. sub cgi (;$$) { #{{{
  465. my $q=shift;
  466. my $session=shift;
  467. if (! $q) {
  468. eval q{use CGI; use CGI::Session};
  469. error($@) if $@;
  470. $q=CGI->new;
  471. run_hooks(cgi => sub { shift->($q) });
  472. }
  473. my $do=$q->param('do');
  474. if (! defined $do || ! length $do) {
  475. my $error = $q->cgi_error;
  476. if ($error) {
  477. error("Request not processed: $error");
  478. }
  479. else {
  480. error("\"do\" parameter missing");
  481. }
  482. }
  483. # Things that do not need a session.
  484. if ($do eq 'recentchanges') {
  485. cgi_recentchanges($q);
  486. return;
  487. }
  488. elsif ($do eq 'hyperestraier') {
  489. cgi_hyperestraier();
  490. }
  491. # Need to lock the wiki before getting a session.
  492. lockwiki();
  493. if (! $session) {
  494. CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
  495. my $oldmask=umask(077);
  496. $session = CGI::Session->new("driver:DB_File", $q,
  497. { FileName => "$config{wikistatedir}/sessions.db" });
  498. umask($oldmask);
  499. }
  500. # Auth hooks can sign a user in.
  501. if ($do ne 'signin' && ! defined $session->param("name")) {
  502. run_hooks(auth => sub {
  503. shift->($q, $session)
  504. });
  505. if (defined $session->param("name")) {
  506. # Make sure whatever user was authed is in the
  507. # userinfo db.
  508. if (! userinfo_get($session->param("name"), "regdate")) {
  509. userinfo_setall($session->param("name"), {
  510. email => "",
  511. password => "",
  512. regdate => time,
  513. });
  514. }
  515. }
  516. }
  517. # Everything below this point needs the user to be signed in.
  518. if (((! $config{anonok} || $do eq 'prefs') &&
  519. (! defined $session->param("name") ||
  520. ! userinfo_get($session->param("name"), "regdate")))
  521. || $do eq 'signin') {
  522. if ($do ne 'signin' && ! defined $session->param("postsignin")) {
  523. $session->param(postsignin => $ENV{QUERY_STRING});
  524. }
  525. cgi_signin($q, $session);
  526. # Force session flush with safe umask.
  527. my $oldmask=umask(077);
  528. $session->flush;
  529. umask($oldmask);
  530. return;
  531. }
  532. elsif (defined $session->param("postsignin")) {
  533. cgi_postsignin($q, $session);
  534. }
  535. if (defined $session->param("name") && userinfo_get($session->param("name"), "banned")) {
  536. print $q->header(-status => "403 Forbidden");
  537. $session->delete();
  538. print "You are banned.";
  539. exit;
  540. }
  541. if ($do eq 'create' || $do eq 'edit') {
  542. cgi_editpage($q, $session);
  543. }
  544. elsif ($do eq 'prefs') {
  545. cgi_prefs($q, $session);
  546. }
  547. elsif ($do eq 'blog') {
  548. my $page=titlepage(decode_utf8($q->param('title')));
  549. # if the page already exists, munge it to be unique
  550. my $from=$q->param('from');
  551. my $add="";
  552. while (exists $pagecase{lc "$from/$page$add"}) {
  553. $add=1 unless length $add;
  554. $add++;
  555. }
  556. $q->param('page', $page.$add);
  557. # now run same as create
  558. $q->param('do', 'create');
  559. cgi_editpage($q, $session);
  560. }
  561. else {
  562. error("unknown do parameter");
  563. }
  564. } #}}}
  565. sub userlink ($) { #{{{
  566. my $user=shift;
  567. eval q{use CGI 'escapeHTML'};
  568. error($@) if $@;
  569. if ($user =~ m!^https?://! &&
  570. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  571. # Munge user-urls, as used by eg, OpenID.
  572. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  573. my $display=$oid->display;
  574. # Convert "user.somehost.com" to "user [somehost.com]".
  575. if ($display !~ /\[/) {
  576. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  577. }
  578. $display=~s!^https?://!!; # make sure this is removed
  579. return "<a href=\"$user\">".escapeHTML($display)."</a>";
  580. }
  581. else {
  582. return htmllink("", "", escapeHTML($user), 1);
  583. }
  584. } #}}}
  585. 1