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