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