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