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