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