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