summaryrefslogtreecommitdiff
path: root/IkiWiki/CGI.pm
blob: af3bb8a4aca307f84bc63914978f312c6dddc301 (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 => \@editable_locs, value => $best_loc);
  409. $form->field(name => "type", type => 'select',
  410. options => \@page_types);
  411. $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
  412. }
  413. elsif ($form->field("do") eq "edit") {
  414. check_canedit($page, $q, $session);
  415. if (! defined $form->field('editcontent') ||
  416. ! length $form->field('editcontent')) {
  417. my $content="";
  418. if (exists $pagesources{$page}) {
  419. $content=readfile(srcfile($pagesources{$page}));
  420. $content=~s/\n/\r\n/g;
  421. }
  422. $form->field(name => "editcontent", value => $content,
  423. force => 1);
  424. }
  425. $form->tmpl_param("page_select", 0);
  426. $form->field(name => "page", type => 'hidden');
  427. $form->field(name => "type", type => 'hidden');
  428. $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
  429. }
  430. print $form->render(submit => \@buttons);
  431. }
  432. else {
  433. # save page
  434. check_canedit($page, $q, $session);
  435. my $content=$form->field('editcontent');
  436. $content=~s/\r\n/\n/g;
  437. $content=~s/\r/\n/g;
  438. $config{cgi}=0; # avoid cgi error message
  439. eval { writefile($file, $config{srcdir}, $content) };
  440. $config{cgi}=1;
  441. if ($@) {
  442. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  443. force => 1);
  444. $form->tmpl_param("failed_save", 1);
  445. $form->tmpl_param("error_message", $@);
  446. $form->field("editcontent", value => $content, force => 1);
  447. $form->field(name => "comments", value => $form->field('comments'), force => 1);
  448. $form->field("do", "edit)");
  449. $form->tmpl_param("page_select", 0);
  450. $form->field(name => "page", type => 'hidden');
  451. $form->field(name => "type", type => 'hidden');
  452. $form->title(sprintf(gettext("editing %s"), $page));
  453. print $form->render(submit => \@buttons);
  454. return;
  455. }
  456. if ($config{rcs}) {
  457. my $message="";
  458. if (defined $form->field('comments') &&
  459. length $form->field('comments')) {
  460. $message=$form->field('comments');
  461. }
  462. if ($newfile) {
  463. rcs_add($file);
  464. }
  465. # prevent deadlock with post-commit hook
  466. unlockwiki();
  467. # presumably the commit will trigger an update
  468. # of the wiki
  469. my $conflict=rcs_commit($file, $message,
  470. $form->field("rcsinfo"),
  471. $session->param("name"), $ENV{REMOTE_ADDR});
  472. if (defined $conflict) {
  473. $form->field(name => "rcsinfo", value => rcs_prepedit($file),
  474. force => 1);
  475. $form->tmpl_param("page_conflict", 1);
  476. $form->field("editcontent", value => $conflict, force => 1);
  477. $form->field(name => "comments", value => $form->field('comments'), force => 1);
  478. $form->field("do", "edit)");
  479. $form->tmpl_param("page_select", 0);
  480. $form->field(name => "page", type => 'hidden');
  481. $form->field(name => "type", type => 'hidden');
  482. $form->title(sprintf(gettext("editing %s"), $page));
  483. print $form->render(submit => \@buttons);
  484. return;
  485. }
  486. else {
  487. # Make sure that the repo is up-to-date;
  488. # locking prevents the post-commit hook
  489. # from updating it.
  490. rcs_update();
  491. }
  492. }
  493. else {
  494. require IkiWiki::Render;
  495. refresh();
  496. saveindex();
  497. }
  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. sub cgi_getsession ($) { #{{{
  504. my $q=shift;
  505. eval q{use CGI::Session};
  506. CGI::Session->name("ikiwiki_session_".encode_utf8($config{wikiname}));
  507. my $oldmask=umask(077);
  508. my $session = CGI::Session->new("driver:DB_File", $q,
  509. { FileName => "$config{wikistatedir}/sessions.db" });
  510. umask($oldmask);
  511. return $session;
  512. } #}}}
  513. sub cgi_savesession ($) { #{{{
  514. my $session=shift;
  515. # Force session flush with safe umask.
  516. my $oldmask=umask(077);
  517. $session->flush;
  518. umask($oldmask);
  519. } #}}}
  520. sub cgi (;$$) { #{{{
  521. my $q=shift;
  522. my $session=shift;
  523. if (! $q) {
  524. eval q{use CGI};
  525. error($@) if $@;
  526. $q=CGI->new;
  527. run_hooks(cgi => sub { shift->($q) });
  528. }
  529. my $do=$q->param('do');
  530. if (! defined $do || ! length $do) {
  531. my $error = $q->cgi_error;
  532. if ($error) {
  533. error("Request not processed: $error");
  534. }
  535. else {
  536. error("\"do\" parameter missing");
  537. }
  538. }
  539. # Things that do not need a session.
  540. if ($do eq 'recentchanges') {
  541. cgi_recentchanges($q);
  542. return;
  543. }
  544. elsif ($do eq 'hyperestraier') {
  545. cgi_hyperestraier();
  546. }
  547. # Need to lock the wiki before getting a session.
  548. lockwiki();
  549. if (! $session) {
  550. $session=cgi_getsession($q);
  551. }
  552. # Auth hooks can sign a user in.
  553. if ($do ne 'signin' && ! defined $session->param("name")) {
  554. run_hooks(auth => sub {
  555. shift->($q, $session)
  556. });
  557. if (defined $session->param("name")) {
  558. # Make sure whatever user was authed is in the
  559. # userinfo db.
  560. if (! userinfo_get($session->param("name"), "regdate")) {
  561. userinfo_setall($session->param("name"), {
  562. email => "",
  563. password => "",
  564. regdate => time,
  565. }) || error("failed adding user");
  566. }
  567. }
  568. }
  569. if (defined $session->param("name") &&
  570. userinfo_get($session->param("name"), "banned")) {
  571. print $q->header(-status => "403 Forbidden");
  572. $session->delete();
  573. print gettext("You are banned.");
  574. cgi_savesession($session);
  575. }
  576. elsif ($do eq 'signin') {
  577. cgi_signin($q, $session);
  578. cgi_savesession($session);
  579. }
  580. elsif (defined $session->param("postsignin")) {
  581. cgi_postsignin($q, $session);
  582. }
  583. elsif ($do eq 'prefs') {
  584. cgi_prefs($q, $session);
  585. }
  586. elsif ($do eq 'create' || $do eq 'edit') {
  587. cgi_editpage($q, $session);
  588. }
  589. elsif ($do eq 'blog') {
  590. my $page=titlepage(decode_utf8($q->param('title')));
  591. $page=~s/(\/)/"__".ord($1)."__"/eg; # escape slashes too
  592. # if the page already exists, munge it to be unique
  593. my $from=$q->param('from');
  594. my $add="";
  595. while (exists $pagecase{lc "$from/$page$add"}) {
  596. $add=1 unless length $add;
  597. $add++;
  598. }
  599. $q->param('page', $page.$add);
  600. # now run same as create
  601. $q->param('do', 'create');
  602. cgi_editpage($q, $session);
  603. }
  604. elsif ($do eq 'postsignin') {
  605. error(gettext("login failed, perhaps you need to turn on cookies?"));
  606. }
  607. else {
  608. error("unknown do parameter");
  609. }
  610. } #}}}
  611. sub userlink ($) { #{{{
  612. my $user=shift;
  613. eval q{use CGI 'escapeHTML'};
  614. error($@) if $@;
  615. if ($user =~ m!^https?://! &&
  616. eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
  617. # Munge user-urls, as used by eg, OpenID.
  618. my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
  619. my $display=$oid->display;
  620. # Convert "user.somehost.com" to "user [somehost.com]".
  621. if ($display !~ /\[/) {
  622. $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
  623. }
  624. # Convert "http://somehost.com/user" to "user [somehost.com]".
  625. if ($display !~ /\[/) {
  626. $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
  627. }
  628. $display=~s!^https?://!!; # make sure this is removed
  629. return "<a href=\"$user\">".escapeHTML($display)."</a>";
  630. }
  631. else {
  632. return htmllink("", "", escapeHTML(
  633. length $config{userdir} ? $config{userdir}."/".$user : $user
  634. ), noimageinline => 1);
  635. }
  636. } #}}}
  637. 1