/[pub]/suikawiki/script/wiki.cgi
Suika

Diff of /suikawiki/script/wiki.cgi

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1.1.1 by wakaba, Sun Jun 2 04:26:22 2002 UTC revision 1.44 by w, Wed Jan 1 12:30:24 2003 UTC
# Line 1  Line 1 
1  #!/usr/local/bin/perl  #!/usr/bin/perl
2  #!perl  # wiki.cgi - This is YukiWiki, yet another Wiki clone.
3  #  #
4  # wiki.cgi - This is YukiWiki, yet another Wiki clone.  # This program is free software; you can redistribute it and/or
5  #  # modify it under the same terms as Perl itself.
6  # Copyright (C) 2000-2002 by Hiroshi Yuki.  
7  # <hyuki@hyuki.com>  use strict;
8  # http://www.hyuki.com/yukiwiki/  use lib qw(./lib);
9  #  use CGI::Carp qw(fatalsToBrowser);
10  # This program is free software; you can redistribute it and/or  
11  # modify it under the same terms as Perl itself.  require 'wikidata/suikawiki-config.ph';
12  #  use Yuki::DiffText qw(difftext);
13  ##############################  use Fcntl;
14  #  ##############################
15  # walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.  my %fmt;        ## formatter objects
16  #  my %embed_command = (
17  # WalWikiの現バージョンは、YukiWiki 2.0.beta1をベースにしています。          searched        => '^\[\[#searched:([^\]]+)\]\]$',
18  #          form    => qr/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
19  # * 更新内容  );
20  #  our ($modifier_dbtype,$url_cgi,%uri,%PathTo,$use_exists);
21  # 2.0.beta1.wal.1 on 2002/05/19,22:32:19  our (%PageName,$kanjicode,$lang,%fixedpage);
22  # (1) Footerの変更  
23  # (2) WikiNameの拡張 : PerlCEも包含、PPMInstallは含まない  ##############################
24  # (3) 別名リンク([別名 URL])に対応。  my $info_LastModified = 'LastModified';
25  # (4) ISBNをアマゾン.jpのAsociateプログラムリンクに変換。  my $info_IsFrozen = 'IsFrozen';
26  # (5) [[#box:InterWikiName]]でInterWikiなテキストボックス生成  ##############################
27  # (6) HTMLモード対応。  my %form;
28  #  my %database;
29  # 旧2.0.alpha0.wal.3版までの修正の内、以下に変更があります。  my %infobase;
30  # ・以下はYukiWiki2に実装されたため、独自コードはなくなりました。  my %diffbase;
31  #   - インラインの画像変換  my %interwiki;
32  #   - YukiWikiDB対応  ##############################
33  #   - テーブル  my %page_command = (
34  #   - DB関連モジュールuseのeval化      $PageName{IndexPage} => 'index',
35  #   - BracketNameによるキーからブラケットを排除      $PageName{RssPage} => 'rss',
36  # ・ISBN番号への対応はWalWiki2.0より、InterWikiへのAdd-Onになりました。      AdminChangePassword => 'adminchangepasswordform',
37  #   [[ISBN http://www.amazon.co.jp/exec/obidos/ASIN/isbn($1)/walrdigi-22]]のように登録。  );
38  #  my %command_do = (
39  #=======================================      read => \&do_read,
40        TEXT_CSS => \&do_output_css,
41  # Walrus add (debug) start      edit => \&do_edit,
42  my $walrus_log;      adminedit => \&do_adminedit,
43  my $walrus_debugging = 0;      adminchangepasswordform => \&do_adminchangepasswordform,
44  # Walrus add (debug) end      adminchangepassword => \&do_adminchangepassword,
45        write => \&do_write,
46  # Libraries.      index => \&do_index,
47  use strict;      searchform => \&do_searchform,
48  use lib qw(./WalWiki/lib);      comment => \&do_comment,
49  use CGI qw(:standard);      RandomJump  => \&do_random_jump,
50  use CGI::Carp qw(fatalsToBrowser);      rss => \&do_rss,
51  use Yuki::RSS;      diff => \&do_diff,
52  use Yuki::DiffText qw(difftext);      wikiform    => \&do_wikiform,
53  use Yuki::YukiWikiDB;      map => \&do_map,
54  use AnyDBM_File;  );
55  require 'jcode.pl';  my $UA = '';  ## User agent name
56  # use Jcode;  $| = 1;
57  use Fcntl;  ##############################
58  my $version = '2.0.beta1.2002-05-29';  
59  ##############################  sub main {
60  #      $UA = $main::ENV{HTTP_USER_AGENT};
61  # You MUST modify following '$modifier_...' variables.      &open_db;
62  #      &init_form;
63  my $modifier_mail = ''; # Your mail address, like 'walrus@digit.que.ne.jp'.      if ($command_do{$form{mycmd}}) {
64  my $modifier_url  = ''; # Your web page, like 'http://digit.que.ne.jp/work/'.          &{$command_do{$form{mycmd}}};
65  my $modifier_name = ''; # Your name, like 'Makio Tsukamoto'.      } else {
66  # my $modifier_dbtype = 'AnyDBM_File';  # Fast, not available on some server, page size limited.          &{$command_do{read}};
67  # my $modifier_dbtype = 'dbmopen';      # Fast, not available on some server, page size limited.      }
68  my $modifier_dbtype = 'YukiWikiDB';     # Slow, available on all environment.      &close_db;
69  # my $modifier_sendmail = '/usr/sbin/sendmail -t -n'; # Your sendmail.  }
70  my $modifier_sendmail = ''; # If you don't need mail notification.  
71  my $modifier_dir_data = './WalWiki'; # Your data directory.  sub do_read {
72  my $modifier_rss_title = "WalWiki $walversion";    my $content = $database{$form{mypage}};
73  my $modifier_rss_link = 'http://yourhost/wiki.cgi'; # Blank is not allowed.    #print "content-type:text/plain;charset=euc-jp\n\n".gmtime."Get Lastmodified\n";
74  my $modifier_rss_description = 'This is WalWiki, yet another Wiki clone based on YukiWiki';    my $lm = &get_info($form{mypage}, $info_LastModified);
75  ##############################    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
76  #    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
77  # You MAY modify following variables.    #print gmtime."Search...\n";
78  #    my ($r, $c) = get_search_result ($form{mypage});
79  my $file_touch = "$modifier_dir_data/touched.txt";    my $rl = wiki::referer::list_html ($form{mypage});
80  my $file_resource = "$modifier_dir_data/resource.txt";    my @toc;
81  my $file_FrontPage = "$modifier_dir_data/frontpage.txt";    push @toc, qq(-<a href="#wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</a>) if $c;
82  my $file_conflict = "$modifier_dir_data/conflict.txt";    push @toc, qq(-<a href="#wikipage-referer">@{[&Resource('Referers',escape=>1)]}</a>) if $rl;
83  my $file_format = "$modifier_dir_data/format.txt";      my $cf = 'SuikaWiki/0.9';
84  my $url_cgi = 'wiki.cgi';      ## Should be support at least:
85  my $url_stylesheet = './WalWiki/Theme/wiki.css';      ## - 'SuikaWiki/0.9' CRLF
86  my $icontag = '<img src="./WalWiki/Theme/icon.gif" alt="*" width="40" height="40" />';      ## - 'H2H/' ("0.9" / "1.0" / "1.1") CRLF
87  my $maxrecent = 50;      ## - "/*" WSP* 'W3C-CSS/' ("1.0" / "2.0") "*/" CRLF
88  my $cols = 80;      $cf = $1 if $content =~ s#^(?:/\*\s*|[\#<]\?)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+##s;
89  my $rows = 20;      if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
90  ##############################      #print gmtime."Header...\n";
91  #        &print_header ($form{mypage}, -last_modified => $lm, -expires => time + 120,
92  # You MAY, but do NOT NEED modify following variables.          -content_format => $cf, -noindex => ($cf =~ /obsoleted="yes"/ ? 1 : 0));
93  #          #print "\n". gmtime."Body...\n";
94  my $dataname = "$modifier_dir_data/wiki";        &print_content ($content, content_format => $cf, last_modified => $lm,
95  my $infoname = "$modifier_dir_data/info";          -toc => \@toc);
96  my $diffname = "$modifier_dir_data/diff";        print &text_to_html (q([[#comment]])) if $cf !~ /obsoleted="yes"/ && !$fixedpage{$form{mypage}};
97  my $editchar = '?';      } else {
98  my $subject_delimiter = ' - ';        &print_header($form{mypage}, -expires => time + 120, -last_modified => $lm);
99  my $use_autoimg = 1; # automatically convert image URL into <img> tag.        print "<pre>@{[&escape($content)]}</pre>";
100  my $use_exists = 0; # If you can use 'exists' method for your DB.      }
101  ##############################      if ($c) {
102  my $InterWikiName = 'InterWikiName';        print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};
103  my $RecentChanges = 'RecentChanges';        print $r;
104  my $AdminChangePassword = 'AdminChangePassword';      }
105  my $CompletedSuccessfully = 'CompletedSuccessfully';      if ($rl) {
106  my $FrontPage = 'FrontPage';        print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
107  my $IndexPage = 'IndexPage';      }
108  my $SearchPage = 'SearchPage';          #print "\n". gmtime."Footer...\n";
109  my $CreatePage = 'CreatePage';    &print_footer($form{mypage}, $lm);
110  my $ErrorPage = 'ErrorPage';          #print "\n". gmtime."Fin...\n";
111  my $RssPage = 'RssPage';  }
112  my $AdminSpecialPage = 'Admin Special Page'; # must include spaces.  
113  ##############################  sub do_output_css {
114  # my $wiki_name = '\b([A-Z][a-z]+([A-Z][a-z]+)+)\b';        # Walrus del (2)    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
115  my $wiki_name   = '\b([A-Z][a-z]+([A-Z][a-z]*)+)\b';        # Walrus add (2)    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
116  my $bracket_name = '\[\[(\S+?)\]\]';    my $content = $database{$form{mypage}};
117  my $embedded_name = '\[\[(#\S+?)\]\]';    if ($content =~ m#^\s*/\*\s*W3C-CSS#) {
118  my $interwiki_definition = '\[\[(\S+?)\ (\S+?)\]\]';      my $lm = gmtime &get_info($form{mypage}, $info_LastModified);
119  my $interwiki_name = '([^:]+):([^:].*)';      print "Content-Type: text/css; charset=@{[&get_charset_name($kanjicode)]}\n";
120  ##############################      print "Last-Modified: $lm\n";
121  my $embed_comment = '[[#comment]]';      print "Expires: @{[scalar gmtime time+3600]}\n";    ## TODO: don't use asctime
122  my $embed_rcomment = '[[#rcomment]]';      print "\n";
123  my $embed_interwiki = '^\[\[#(box|text|password):(\S+)\]\]$';    # Walrus add (5)      print $content;
124  ##############################    } else {
125  my $info_LastModified = 'LastModified';      print "Status: 406 Unsupported Media Type\n";
126  my $info_IsFrozen = 'IsFrozen';      &print_header('WikiPageIsNotCSS', -noindex => 1);
127  my $info_AdminPassword = 'AdminPassword';      &print_content($database{WikiPageIsNotCSS});
128  ##############################      &print_footer('WikiPageIsNotCSS');
129  my $kanjicode = 'euc';    }
130  my $charset = 'EUC-JP';  }
131  my $lang = 'ja';  
132  my %fixedpage = (  sub id_and_name ($) {
133      $IndexPage => 1,      my $name = shift;
134      $CreatePage => 1,      if ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer#) {
135      $ErrorPage => 1,        qq{id="$name"><a name="$name"></a};
136      $RssPage => 1,      } else {
137      $RecentChanges => 1,          qq{id="$name"};
138      $SearchPage => 1,      }
139      $AdminChangePassword => 1,  }
140      $CompletedSuccessfully => 1,  
141      $FrontPage => 1,  sub do_edit {
142  );      my ($page) = &unarmor_name(&armor_name($form{mypage}));
143  my %form;      if (not &is_editable($page)) {
144  my %database;          &print_header($page, -noindex => 1);
145  my %infobase;          &print_message(&Resource('Error:ThisPageIsUneditable'));
146  my %diffbase;      } elsif (&is_frozen($page)) {
147  my %resource;          &print_header($page, -noindex => 1);
148  my %interwiki;          &print_message(&Resource('Error:ThisPageIsUneditable'));
149  ##############################      } else {
150  my %page_command = (          &print_header($page, -noindex => 1, -expires => time+60);
151      $IndexPage => 'index',          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);
152      $SearchPage => 'searchform',      }
153      $CreatePage => 'create',      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
154      $RssPage => 'rss',      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
155      $AdminChangePassword => 'adminchangepasswordform',      my ($r, $c) = get_search_result ($form{mypage});
156      $FrontPage => 'FrontPage',      my $rl = wiki::referer::list_html ($form{mypage});
157  );      if ($c) {
158  my %command_do = (        print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};
159      read => \&do_read,        print $r;
160      edit => \&do_edit,      }
161      adminedit => \&do_adminedit,      if ($rl) {
162      adminchangepasswordform => \&do_adminchangepasswordform,        print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
163      adminchangepassword => \&do_adminchangepassword,      }
164      write => \&do_write,      &print_footer($page);
165      index => \&do_index,  }
166      searchform => \&do_searchform,  
167      search => \&do_search,  sub do_adminedit {
168      create => \&do_create,      my ($page) = &unarmor_name(&armor_name($form{mypage}));
169      createresult => \&do_createresult,      &print_header($page, -noindex => 1);
170      FrontPage => \&do_FrontPage,      if (not &is_editable($page)) {
171      comment => \&do_comment,          &print_message(&Resource('Error:ThisPageIsUneditable'));
172      rss => \&do_rss,      } else {
173      diff => \&do_diff,          &print_message(&Resource('Error:PasswordIsNotSpecified'));
174      interwikibox => \&do_interwiki_box, # Walrus add (5)          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);
175  );      }
176  ##############################      &print_footer($page);
177  my @ignore_html_page = ('FrontPage');        # Walrus add (6)  }
178  my @ignore_html_tags = ('a', 'br', 'img');   # Walrus add (6)  
179  my $walversion = '2.0.beta1.wal.1';          # Walrus add (1)  sub do_adminchangepasswordform {
180  ##############################      &print_header('AdminChangePassword', -noindex => 1);
181  # &test_convert;      &print_passwordform;
182  &main;      &print_footer('AdminChangePassword');
183  exit(0);  }
184  ##############################  
185    sub do_adminchangepassword {
186  sub main {      if ($form{mynewpassword} ne $form{mynewpassword2}) {
187      &init_resource;          &print_error(&Resource('Error:PasswordMismatch'));
188      &open_db;      }
189      &init_form;      my ($validpassword_crypt) = &get_info($PageName{AdminSpecialPage}, 'AdminPassword');
190      &init_InterWikiName;      if ($validpassword_crypt) {
191      if ($command_do{$form{mycmd}}) {          if (not &valid_password($form{myoldpassword})) {
192          &{$command_do{$form{mycmd}}};  #            &send_mail_to_admin(<<"EOD", "AdminChangePassword");
193      } else {  #myoldpassword=$form{myoldpassword}
194          &do_FrontPage;  #mynewpassword=$form{mynewpassword}
195      }  #mynewpassword2=$form{mynewpassword2}
196      &close_db;  #EOD
197  }              &print_error(&Resource('Error:PasswordIsIncorrect'));
198            }
199  sub do_read {      }
200      &print_header($form{mypage});      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
201      &print_content($database{$form{mypage}});      my (@token) = ('0'..'9', 'A'..'Z', 'a'..'z');
202      &print_footer($form{mypage});      my $salt1 = $token[(time | $$) % scalar(@token)];
203  }      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
204        my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
205  sub do_edit {      &set_info($PageName{AdminSpecialPage}, 'AdminPassword', $crypted);
206      my ($page) = &unarmor_name(&armor_name($form{mypage}));  
207      &print_header($page);      &print_header('CompletedSuccessfully', -noindex => 1);
208      if (not &is_editable($page)) {      &print_message(&Resource('Error:PasswordIsChanged'));
209          &print_message($resource{cantchange});      &print_footer('CompletedSuccessfully');
210      } elsif (&is_frozen($page)) {  }
211          &print_message($resource{cantchange});  
212      } else {  sub do_index {
213          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
214      }    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
215      &print_footer($page);      &print_header($PageName{IndexPage});
216  }      print qq(<ul>);
217        foreach my $page (sort keys %database) {
218  sub do_adminedit {          if (&is_editable($page)) {
219      my ($page) = &unarmor_name(&armor_name($form{mypage}));              print qq(<li><a href="$url_cgi?@{[&encode($page)]}">@{[&escape($page)]}</a>@{[&escape(&get_subjectline($page))]}</li>);
220      &print_header($page);          }
221      if (not &is_editable($page)) {      }
222          &print_message($resource{cantchange});      print qq(</ul>);
223      } else {      my ($r, $c) = get_search_result ($form{mypage});
224          &print_message($resource{passwordneeded});      if ($c) {
225          &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);        print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};
226      }        print $r;
227      &print_footer($page);      }
228  }      my $rl = wiki::referer::list_html ($form{mypage});
229        if ($rl) {
230  sub do_adminchangepasswordform {          print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
231      &print_header($AdminChangePassword);      }
232      &print_passwordform;      &print_footer($PageName{IndexPage});
233      &print_footer($AdminChangePassword);  }
234  }  
235    sub do_write {
236  sub do_adminchangepassword {      if (&frozen_reject()) {
237      if ($form{mynewpassword} ne $form{mynewpassword2}) {          return;
238          &print_error($resource{passwordmismatcherror});      }
239      }  
240      my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_AdminPassword);      if (not &is_editable($form{mypage})) {
241      if ($validpassword_crypt) {          &print_header($form{mypage}, -noindex => 1);
242          if (not &valid_password($form{myoldpassword})) {          &print_message(&Resource('Error:ThisPageIsUneditable'));
243              &send_mail_to_admin(<<"EOD", "AdminChangePassword");          &print_footer($form{mypage});
244  myoldpassword=$form{myoldpassword}          return;
245  mynewpassword=$form{mynewpassword}      }
246  mynewpassword2=$form{mynewpassword2}  
247  EOD      if (&conflict($form{mypage}, $form{mymsg})) {
248              &print_error($resource{passworderror});          return;
249          }      }
250      }  
251      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);      # Making diff
252      my (@token) = ('0'..'9', 'A'..'Z', 'a'..'z');      {
253      my $salt1 = $token[(time | $$) % scalar(@token)];          &open_diff;
254      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];          my @msg1 = split(/\n/, $database{$form{mypage}});
255      my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");          my @msg2 = split(/\n/, $form{mymsg});
256      &set_info($AdminSpecialPage, $info_AdminPassword, $crypted);          $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);
257            &close_diff;
258      &print_header($CompletedSuccessfully);      }
259      &print_message($resource{passwordchanged});  
260      &print_footer($CompletedSuccessfully);      if ($form{mymsg}) {
261  }          $database{$form{mypage}} = $form{mymsg};
262            #&send_mail_to_admin($form{mypage}, "Modify");
263  sub do_index {          if ($form{mytouch}) {
264      &print_header($IndexPage);              &set_info($form{mypage}, $info_LastModified, time);
265      print qq(<ul>);              &update_recent_changes;
266      foreach my $page (sort keys %database) {          }
267          if (&is_editable($page)) {          &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});
268              print qq(<li><a href="$url_cgi?@{[&encode($page)]}">$page</a>@{[&escape(&get_subjectline($page))]}</li>);          my $fragment = '';
269              # print qq(<li>@{[&get_info($page, $info_IsFrozen)]}</li>);          $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
270              # print qq(<li>@{[0 + &is_frozen($page)]}</li>);          if ($form{__comment_anchor_index}) {
271          }              $fragment .= qq(#anchor-$form{__comment_anchor_index});
272      }          } elsif ($form{__wikiform_anchor_index}) {
273      print qq(</ul>);              $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
274      &print_footer($IndexPage);          }
275  }          &print_header('CompletedSuccessfully', -noindex => 1, -goto => $url_cgi.'?mycmd='.&encode($form{after_edit_cmd}||'read').';mypage='.&encode($form{mypage}).qq(;x-param=@{[time.[0..9]->[rand 10]]}$fragment));
276            &print_message(&Resource('Error:SavedSuccessfully'));
277  sub do_write {          &print_content(&Resource('Error:ContinueReading')." @{[&armor_name($form{mypage})]}");
278      if (&frozen_reject()) {          &print_footer('CompletedSuccessfully');
279          return;      } else {
280      }          #&send_mail_to_admin($form{mypage}, "Delete");
281            delete $database{$form{mypage}};
282      if (not &is_editable($form{mypage})) {          delete $infobase{$form{mypage}};
283          &print_header($form{mypage});          if ($form{mytouch}) {
284          &print_message($resource{cantchange});              &update_recent_changes;
285          &print_footer($form{mypage});          }
286          return;          &print_header($form{mypage}, -noindex => 1);
287      }          &print_message(&Resource('Error:PageIsDeletedSuccessfully'));
288            &print_footer($form{mypage});
289      if (&conflict($form{mypage}, $form{mymsg})) {      }
290          return;  }
291      }  
292    sub get_search_result ($;%) {
293      # Making diff    my $word = lc shift;
294      {    my %option = @_;
295          &open_diff;    my @r;
296          my @msg1 = split(/\n/, $database{$form{mypage}});    foreach my $page (keys %database) {
297          my @msg2 = split(/\n/, $form{mymsg});      next if !$option{-match_myself} && ($page eq $word);
298          $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);      my $content = lc $database{$page};
299          &close_diff;      if (index (lc $page, $word) > -1) {
300      }        my $c = $content =~ s/\Q$word\E//g;
301          push @r, [$page, $c+20];
302      if ($form{mymsg}) {      } elsif (index ($word, lc $page) > -1) {
303          $database{$form{mypage}} = $form{mymsg};        my $c = $content =~ s/\Q$word\E//g;
304          &send_mail_to_admin($form{mypage}, "Modify");        push @r, [$page, $c+10];
305          if ($form{mytouch}) {      } elsif (my $c = $content =~ s/\Q$word\E//g) {
306              &set_info($form{mypage}, $info_LastModified, '' . localtime);        push @r, [$page, $c];
307              &update_recent_changes;      }
308          }    }
309          &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});    #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
310          &print_header($CompletedSuccessfully);    my $r = join "\n", map {qq(<li>[$_->[1]] <a href ="$url_cgi?@{[&encode($_->[0])]}" class="wiki">@{[&escape($_->[0])]}</a> <span class="wikipage-summary">@{[&escape(&get_subjectline($_->[0]))]}</span></li>)} sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]} @r;
311          &print_message($resource{saved});    $r = qq|<ul class="search-result">$r</ul>| if $r;
312          &print_content("$resource{continuereading} @{[&armor_name($form{mypage})]}");    wantarray? ($r, scalar @r): $r;
313          &print_footer($CompletedSuccessfully);  }
314      } else {  
315          &send_mail_to_admin($form{mypage}, "Delete");  sub do_random_jump {
316          delete $database{$form{mypage}};    my @list = keys %database;
317          delete $infobase{$form{mypage}};    my $name = &encode ($list[rand @list]);
318          if ($form{mytouch}) {    my $scheme = 'http';
319              &update_recent_changes;    $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
320          }    print "Location: $scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi?$name\n";
321          &print_header($form{mypage});    print "\n";
322          &print_message($resource{deleted});  }
323          &print_footer($form{mypage});  
324      }  sub print_error {
325  }      my ($msg) = @_;
326        &print_header($PageName{ErrorPage}, -noindex => 1);
327  sub do_searchform {      print qq(<p><strong class="error">$msg</strong></p>);
328      &print_header($SearchPage);      &print_footer($PageName{ErrorPage});
329      &print_searchform("");      exit(0);
330      &print_footer($SearchPage);  }
331  }  
332    sub print_header ($;%) {
333  sub do_search {      my ($page, %option) = @_;
334      my $word = &escape($form{mymsg});      my @head;
335      &print_header($SearchPage);      $option{body_class} = &is_frozen($page) ? 'frozen' : 'normal';
336      &print_searchform($word);      $option{body_class} .= " wiki-page-obsoleted" if $option{-content_format} =~ /obsoleted="yes"/;
337      my $counter = 0;      if ($option{-goto}) {
338      foreach my $page (sort keys %database) {        if ($UA =~ m#Opera|MSIE 2\.#) {
339          next if $page =~ /^$RecentChanges$/;            ## WARNING: This code may output unsafe HTML document if
340          if ($database{$page} =~ /\Q$form{mymsg}\E/ or $page =~ /\Q$form{mymsg}\E/) {            ##          $option{-goto} is not clean.
341              if ($counter == 0) {            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
342                  print qq|<ul>|;            print qq{Refresh: 0; url=$option{-goto}\n};
343              }            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
344              print qq(<li><a href ="$url_cgi?@{[&encode($page)]}">$page</a>@{[&escape(&get_subjectline($page))]}</li>);        } else {
345              $counter++;            $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
346          }            print qq{Refresh: 0; url="$option{-goto}"\n};
347      }            push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;">);
348      if ($counter == 0) {        }
349          &print_message($resource{notfound});      }
350      } else {      print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
351          print qq|</ul>|;      if ($option{-expires}) {
352      }        print qq{Expires: @{[scalar gmtime $option{-expires}]}\n};
353      &print_footer($SearchPage);      }
354  }      if ($UA =~ m#Mozilla/2#) {
355            my $ct = qq{text/html; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
356  sub do_create {          print qq{Content-Type: $ct\n};
357      &print_header($CreatePage);          push @head, qq{<meta http-equiv="content-type" content="$ct">};
358      print <<"EOD";      } elsif ($UA =~ m#Infomosaic#) {
359  <form action="$url_cgi" method="post">          print qq{Content-Type: text/html\n};
360      <input type="hidden" name="mycmd" value="edit">      } else {
361      <strong>$resource{newpagename}</strong><br>          print qq{Content-Type: text/html; charset=@{[&get_charset_name($kanjicode)]}\n};
362      <input type="text" name="mypage" value="" size="20">      }
363      <input type="submit" value="$resource{createbutton}"><br>      push @head, qq(<title>@{[&escape($page)]}</title>);
364  </form>      if ($UA !~ m#Mozilla/[1-4]\.# || $UA =~ m#MSIE (?:[4-9]\.|\d\d)#) {
365  EOD        push @head, qq(<link rel="stylesheet" type="text/css" href="@{[&escape($uri{wiki}.'?mycmd=TEXT_CSS;mypage='.&encode($PageName{DefaultStyleForHTML}).';x-lm='.&get_info($PageName{DefaultStyleForHTML}, $info_LastModified))]}");
366      &print_footer($CreatePage);      }
367  }      push @head, q(<meta name="ROBOTS" content="NOINDEX">) if $option{-noindex};
368        my ($Links, $links) = &make_navigate_links ($page);
369  sub do_FrontPage {      #print $Links;      ## Link: fields
370      open(FILE, $file_FrontPage) or &print_error("($file_FrontPage)");      $links = join "\n", (@head, $links);
371      my $content = join('', <FILE>);      print <<"EOD";
372      &code_convert(\$content, $kanjicode);  Content-Language: $lang
373      close(FILE);  Content-Style-Type: text/css
374      &print_header($FrontPage);  
375      &print_content($content);  <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
376      &print_footer($FrontPage);  "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->
377  }  <html lang="$lang" class="$option{body_class}">
378    <head profile="http://suika.fam.cx/~wakaba/-temp/wiki/wiki?WikiHTMLMetaProfile">
379  sub print_error {  $links
380      my ($msg) = @_;  </head>
381      &print_header($ErrorPage);  <body class="$option{body_class}">
382      print qq(<p><strong class="error">$msg</strong></p>);  EOD
383      &print_footer($ErrorPage);      &print_navigate_links ($page);
384      exit(0);      print <<EOD;
385  }  <h1 class="header">@{[&escape($page)]}</h1>
386    EOD
387  sub print_header {  }
388      my ($page) = @_;  
389      my $bodyclass = "normal";  sub get_charset_name ($;%) {
390      my $editable = 0;      my ($charset, %option) = (lc shift, @_);
391      my $admineditable = 0;      if ($charset =~ 'euc') {
392      if (&is_frozen($page) and $form{mycmd} =~ /^(read|write)$/) {          $charset = $option{compatible} ? 'x-euc-jp' : 'euc-jp';
393          $editable = 0;      } elsif ($charset =~ 'sjis' || $charset =~ 'shift') {
394          $admineditable = 1;          $charset = $option{compatible} ? 'x-sjis' : 'shift_jis';
395          $bodyclass = "frozen";      } elsif ($charset =~ 'jis') {
396      } elsif (&is_editable($page) and $form{mycmd} =~ /^(read|write)$/) {          $charset = 'iso-2022-jp';
397          $admineditable = 1;      }
398          $editable = 1;      $charset;
399      } else {  }
400          $editable = 0;  
401      }  sub print_navigate_links (@) {
402      my $cookedpage = &encode($page);    my ($page) = @_;
403      print <<"EOD";    my $editable = (&is_editable($page) && !&is_frozen($page)) ? 1 : 0;
404  Content-type: text/html; charset=$charset    my $cookedpage = &encode($page);
405      print <<EOH;
406  <!DOCTYPE html  <div class="tools">
407      PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"      @{[ $editable
408      "http://www.w3.org/TR/html4/loose.dtd">          ? qq(<a title="@{[&Resource('EditThisPageLong',escape=>1)]}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E" class="wiki-cmd">@{[&Resource('EditThisPage',escape=>1)]}</a> | )
409  <html lang="$lang">          : qq()
410  <head>      ]}
411      <meta http-equiv="Content-Language" content="$lang">      <a href="$url_cgi?mycmd=read;mypage=$cookedpage;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki-cmd" title="@{[&Resource('ViewThisPageLong',escape=>1)]}">@{[&Resource('ViewThisPage',escape=>1)]}</a> |
412      <meta http-equiv="Content-Type" content="text/html; charset=$charset">      <a href="$url_cgi?mycmd=map;mypage=$cookedpage" class="wiki-cmd" title="@{[&Resource('ShowMapOfThisPageLong',escape=>1)]}">@{[&Resource('ShowMapOfThisPage',escape=>1)]}</a> |
413      <title>$page @{[&escape(&get_subjectline($page))]}</title>      <a href="$url_cgi?$PageName{CreatePage}" class="wiki" title="@{[&Resource('GoToCreatePageLong',escape=>1)]}">@{[&Resource('GoToCreatePage',escape=>1)]}</a> |
414      <link rel="index" href="$url_cgi?$IndexPage">      <a href="$url_cgi?$PageName{IndexPage}" class="wiki" title="@{[&Resource('GoToIndexPageLong',escape=>1)]}">@{[&Resource('GoToIndexPage',escape=>1)]}</a> |
415      <link rev="made" href="mailto:$modifier_mail">      <a href="$url_cgi?$PageName{FrontPage}" class="wiki" title="@{[&Resource('GoToHomePageLong',escape=>1)]}">@{[&Resource('GoToHomePage',escape=>1)]}</a> |
416      <link rel="stylesheet" type="text/css" href="$url_stylesheet">      <a href="$url_cgi?$PageName{SearchPage}" class="wiki" title="@{[&Resource('GoToSearchPageLong',escape=>1)]}">@{[&Resource('GoToSearchPage',escape=>1)]}</a> |
417  </head>      <a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink" title="@{[&Resource('GoSomewhereLong',escape=>1)]}">@{[&Resource('GoSomewhere',escape=>1)]}</a> |
418  <body class="$bodyclass">      <a href="$url_cgi?RecentChanges" class="wiki" title="@{[&Resource('GoToRecentChangesLong',escape=>1)]}">@{[&Resource('GoToRecentChanges',escape=>1)]}</a>
419  <div class="tools">  </div>
420      @{[ $admineditable  EOH
421          ? qq(<a title="$resource{admineditthispage}" href="$url_cgi?mycmd=adminedit&amp;mypage=$cookedpage">$resource{admineditbutton}</a> | )  }
422          : qq()  
423      ]}  sub make_navigate_links ($) {
424      @{[ $editable      my $page = shift;
425          ? qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit&amp;mypage=$cookedpage">$resource{editbutton}</a> | )      my @link;
426          : qq()      push @link, {rel=>'edit', href=>"$url_cgi?mycmd=edit;mypage=@{[&encode($page)]}", class=>"wiki-command", title=>&Resource('EditThisPageLink')} if &is_editable ($page) && !&is_frozen ($page);
427      ]}      push @link, {rel=>'edit', href=>"$url_cgi?mycmd=adminedit;mypage=@{[&encode($page)]}", class=>"wiki-command", title=>&Resource('AdminEditThisPageLink')} if &is_editable ($page) || &is_frozen ($page);
428      @{[ $admineditable      push @link, {rel=>'view', href=>"$url_cgi?mycmd=read;mypage=@{[&encode($page)]};x-p=@{[time.[0..9]->[rand 10]]}", class=>'wiki-command', title=>&Resource('ViewThisPageLink')};
429          ? qq(<a href="$url_cgi?mycmd=diff&amp;mypage=$cookedpage">$resource{diffbutton}</a> | )      push @link, {rel=>'myself', href=>"$url_cgi?@{[&encode($page)]}", class=>'wiki', title=>&Resource('GoToMyselfLink')};
430          : qq()      push @link, {rel=>'index', href=>"$url_cgi?$PageName{IndexPage}", class=>'wiki', title=>&Resource('GoToIndexPageLink')};
431      ]}      push @link, {rel=>'home', href=>"$url_cgi?$PageName{FrontPage}", class=>'wiki', title=>&Resource('GoToHomePageLink')};
432      <a href="$url_cgi?$CreatePage">$resource{createbutton}</a> |      push @link, {rel=>'News', href=>"$url_cgi?WikiNews", class=>'wiki', title=>&Resource('GoToWikiNewsLink')};
433      <a href="$url_cgi?$IndexPage">$resource{indexbutton}</a> |      push @link, {rel=>'News', href=>"$url_cgi?RecentChanges", class=>"wiki", title=>&Resource('GoToRecentChangesLink')};
434      <a href="$url_cgi?$RssPage">$resource{rssbutton}</a> |      push @link, {rel=>'News', href=>"$url_cgi?$PageName{RssPage}", class=>"wiki", title=>&Resource('GoToRssPageLink'), type=>'application/xml'};
435      <a href="$url_cgi?$FrontPage">$FrontPage</a> |      push @link, {rel=>'search', href=>"$url_cgi?$PageName{SearchPage}", class=>'wiki', title=>&Resource('GoToSearchPageLink')};
436      <a href="$url_cgi?$SearchPage">$resource{searchbutton}</a> |      push @link, {rel=>'help', href=>"$url_cgi?WikiHelp", class=>'wiki', title=>&Resource('GoToWikiHelpLink')};
437      <a href="$url_cgi?$RecentChanges">$resource{recentchangesbutton}</a>      push @link, {rel=>'copyright', href=>"$url_cgi?WikiPageLicense", class=>'wiki', title=>&Resource('GoToWikiPageLicenseLink')};
438  </div>      push @link, {rel=>'jump', href=>qq(javascript:var%20WikiName=prompt('Please%20input%20the%20WikiName:','','Jump%20to%20SuikaWiki');if(WikiName)%7B_content.location.href='$url_cgi%3F'+encodeURIComponent(WikiName)%7D), class=>'wiki-cmd', title=>&Resource('JumpToLink')};
439  <h1 class="header"><a      push @link, {rel=>'jump', href=>qq(javascript:var%20WikiName=prompt('Please%20input%20the%20WikiName:','','Jump%20to%20SuikaWiki');if(WikiName)%7B_content.location.href='$url_cgi%3Fmycmd=edit;mypage='+encodeURIComponent(WikiName)%7D), class=>'wiki-cmd', title=>&Resource('JumpToEditLink')};
440      title="$resource{searchthispage}"      push @link, {rel=>'lucky', href=>"$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}", class=>'wiki randomlink', title=>&Resource('GoSomewhereLink')};
441      href="$url_cgi?mycmd=search&amp;mymsg=$cookedpage">$page</a>@{[&escape(&get_subjectline($page))]}</h1>      push @link, {rel=>'history', href=>$uri{cvs_wikipage}.do{my $s=$page;$s=~s/(.)/sprintf '%02X', ord $1/ges;$s}.'.txt', title=>&Resource('ViewHistoryOfThisPageLink'),hreflang=>'en'} if $uri{cvs_wikipage};
442  EOD      push @link, {rel=>'history', href=>"$url_cgi?mycmd=diff;mypage=@{[&encode($page)]}", title=>&Resource('ViewDiffOfThisPageLink'), class=>'wiki-command'};
443  }      push @link, {rel=>'contents', href=>"$url_cgi?mycmd=map;mypage=@{[&encode($page)]}", title=>&Resource('ShowMapOfThisPageLink'), class=>'wiki-command'};
444        my ($Links, $links) = ('', '');
445  sub print_footer {      for my $e (@link) {
446      my ($page) = @_;          $links .= qq(<link);
447      $walrus_log = ($walrus_debugging) ? &text_to_html("----\n$walrus_log") : '';    # Walrus add (debug)          $Links .= qq(Link: <$e->{href}>);
448      # Walrus mod (1) start          for my $attr (qw/rel rev href title class type hreflang charset/) {
449      my $mod_info = $modifier_name ? qq(Modified by <a href="$modifier_url">$modifier_name</a>.) : '';              $links .= qq( $attr="@{[&escape($e->{$attr})]}") if $e->{$attr};
450      print <<"EOD";          }
451  <div class="footer">          for my $attr (qw/rel rev title/) {
452  <hr />              $Links .= qq(; $attr="@{[do{$e->{$attr} =~ s/([\\\"])/\\$1/g; $e->{$attr}}]}") if $e->{$attr};
453  <p>          }
454  <a href="http://digit.que.ne.jp/work/">WalWiki</a> $walversion &copy; 2000-2002 by <a href="http://digit.que.ne.jp/">Makio Tsukamoto</a>.<br />          $links .= qq(>\n);
455  based on <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version &copy; 2000-2002 by <a href="http://www.hyuki.com/">Hiroshi Yuki</a>.<br />          $Links .= qq(\n);
456  $mod_info      }
457  </p><p>      wantarray ? ($Links, $links) : $Links;
458  <a href="http://digit.que.ne.jp/work/">$icontag</a>  }
459  </p>  
460  </div>  sub print_footer {
461  $walrus_log <!-- Walrus add (debug) -->      my ($page, $lm) = @_;
462  </body>      my $epage = &encode ($page);
463  </html>    my $cvslog1 = q$Revision$;
464  EOD    my $cvslog2 = q$Date$;
465  #       print <<"EOD";    print_navigate_links ($page);
466  #   <hr>    print <<"EOD";
467  #   <address class="footer">  @{[ $lm ? qq(<div id="wikipage-last-modified">@{[&Resource('LastModified=',escape=>1)]}@{[&_rfc3339_date ($lm)]}</div>) : '' ]}
468  #       <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version  <div class="footer">
469  #       &copy; 2000-2002 by <a href="http://www.hyuki.com/">Hiroshi Yuki</a>.<br />  <a href="http://www.hyuki.com/yukiwiki/" title="YukiWiki 2.0.beta1.2002-05-29 &copy; 2000-2002 by Hiroshi Yuki">@{[&Resource('About:Name:YukiWiki',escape=>1)]}</a> <a href="http://digit.que.ne.jp/work/" title="WalWiki 2.0.beta1.wal.1 &copy; 2000-2002 by Makio Tsukamoto">@{[&Resource('About:Name:WalWiki',escape=>1)]}</a>
470  #       Modified by <a href="$modifier_url">$modifier_name</a>.  <a href="/gate/cvs/wakaba/wiki/" title="@{[&Resource('About:SuikaWiki:JumpToCVS',escape=>1)]} ($cvslog2)">@{[&Resource('About:Name:SuikaWiki',escape=>1)]} $cvslog1</a>
471  #   </address>  </div>
472  #   <p class="footer">  </body>
473  #       <a href="http://www.hyuki.com/yukiwiki/">$icontag</a>  </html>
474  #   </p>  EOD
475  #   </body>  }
476  #   </html>  
477  #   EOD  sub escape {
478      # Walrus mod (1) end      my $s = shift;
479  }      $s =~ s|\r\n|\n|g;
480        $s =~ s|&|&amp;|g;
481  sub escape {      $s =~ s|<|&lt;|g;
482      my $s = shift;      $s =~ s|>|&gt;|g;
483      $s =~ s|\r\n|\n|g;      $s =~ s|"|&quot;|g;
484      $s =~ s|\&|&amp;|g;      return $s;
485      $s =~ s|<|&lt;|g;  }
486      $s =~ s|>|&gt;|g;  
487      $s =~ s|"|&quot;|g;  sub unescape {
488      return $s;      my $s = shift;
489  }      # $s =~ s|\n|\r\n|g;
490        $s =~ s|&lt;|<|g;
491  sub unescape {      $s =~ s|&gt;|>|g;
492      my $s = shift;      $s =~ s|&quot;|"|g;
493      # $s =~ s|\n|\r\n|g;      $s =~ s|&amp;|&|g;
494      $s =~ s|\&amp;|\&|g;      return $s;
495      $s =~ s|\&lt;|\<|g;  }
496      $s =~ s|\&gt;|\>|g;  
497      $s =~ s|\&quot;|\"|g;  sub print_content ($;$) {
498      return $s;      my ($rawcontent, %option) = @_;
499  }      print &text_to_html($rawcontent, toc=>1, %option);
500    }
501  sub print_content {  
502      my ($rawcontent) = @_;  sub text_to_html {
503      print &text_to_html($rawcontent, toc=>1);      my ($txt, %option) = @_;
504  }      my @toc;
505        my @toc2 = @{$option{-toc}||[]};
506  sub text_to_html {      my $tocnum = 0;
507      my ($txt, %option) = @_;      
508      my (@txt) = split(/\n/, $txt);      ## Load constants
509      my (@toc);      my %const;
510      my $tocnum = 0;      if ($option{content_format} =~ /import="([^"]+)"/) {
511      my (@saved, @result);        for (split /\s*,\s*/, $1) {
512      unshift(@saved, "</p>");          my $wp = $database{$_};
513      push(@result, "<p>");          if ($wp =~ m!^\#\?SuikaWikiConst/1.0!) {
514      foreach (@txt) {            wiki::suikawikiconst::to_hash ($wp => \%const);
515          chomp;          }
516          # Walrus mod (6) start        }
517          if ($saved[0] eq '</html>') {      }
518              if (/<\/html>/i) { splice(@saved); }      
519              else { push (@result, &html_to_ignored_html($_)); }      $txt =~ s{__&&([^&]+)&&__}{defined $const{$1}?$const{$1}:qq(__&&$1&&__)}ge;
520          } elsif (/^<html>/i and &is_ignore_html($form{mypage})) {      my (@txt) = split(/\n/, $txt);
521              push(@result, splice(@saved));      my (@saved, @result);
522              push(@saved, '</html>');      unshift(@saved, "</p>");
523          } elsif (/^\*\*(.*)/) {      push(@result, "<p>");
524          # if (/^\*\*(.*)/) {      foreach (@txt) {
525          # Walrus mod (6) end          chomp;
526              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
527              push(@result, splice(@saved), qq(<h3><a name="i$tocnum"> </a>) . &inline($1) . '</h3>');              push(@toc, qq(----- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
528              $tocnum++;              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h6>');
529          } elsif (/^\*(.*)/) {              $tocnum++;
530              push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)]}</a>\n));          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
531              push(@result, splice(@saved), qq(<h2><a name="i$tocnum"> </a>) . &inline($1) . '</h2>');              push(@toc, qq(---- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
532              $tocnum++;              push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h5>');
533          } elsif (/^----/) {              $tocnum++;
534              push(@result, splice(@saved), '<hr>');          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
535          } elsif (/^(-{1,3})(.*)/) {              push(@toc, qq(--- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
536              &back_push('ul', length($1), \@saved, \@result);              push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h4>');
537              push(@result, '<li>' . &inline($2) . '</li>');              $tocnum++;
538          } elsif (/^:([^:]+):(.*)/) {          } elsif (/^\*\*([^\x0D\x0A]*)/) {
539              &back_push('dl', 1, \@saved, \@result);          # if (/^\*\*(.*)/) {
540              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');          # Walrus mod (6) end
541          } elsif (/^(>{1,3})(.*)/) {              push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
542              &back_push('blockquote', length($1), \@saved, \@result);              push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h3>');
543              push(@result, &inline($2));              $tocnum++;
544          } elsif (/^\s*$/) {          } elsif (/^\*([^\x0D\x0A]*)/) {
545              push(@result, splice(@saved));              push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
546              unshift(@saved, "</p>");              push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h2>');
547              push(@result, "<p>");              $tocnum++;
548          } elsif (/^(\s+.*)$/) {          } elsif (/^(={1,6})(.*)/) {
549              &back_push('pre', 1, \@saved, \@result);              &back_push('ol', length($1), \@saved, \@result);
550              push(@result, &escape($1)); # Not &inline, but &escape              push(@result, '<li>' . &inline($2, const => \%const) . '</li>');
551  #       } elsif (/^\,(.*)$/) {             # Walrus del (BF)          } elsif (/^(-{1,6})(.*)/) {
552          } elsif (/^\,(.*?)[\x0D\x0A]*$/) { # Walrus add (BF)            &back_push('ul', length($1), \@saved, \@result);
553              &back_push('table', 1, \@saved, \@result, ' border="1"');            my ($pf, $l) = ('', $2);
554              #######            if (!$main::_EMBEDED && $l =~ s/^\s*\[([0-9]+)\]//) {
555              # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.              my $num = 0+$1;
556              # XXXXX              $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
557              my $tmp = "$1,";            }
558              my @value = map {/^"(.*)"$/ ? scalar($_ = $1, s/""/"/g, $_) : $_} ($tmp =~ /("[^"]*(?:""[^"]*)*"|[^,]*),/g);            push(@result, '<li>' . $pf . &inline ($l, const => \%const) . '</li>');
559              my @align = map {(s/^\s+//) ? ((s/\s+$//) ? ' align="center"' : ' align="right"') : ''} @value;          } elsif (/^:([^:]+):(.*)/) {
560              my @colspan = map {($_ eq '==') ? 0 : 1} @value;              &back_push('dl', 1, \@saved, \@result);
561              for (my $i = 0; $i < @value; $i++) {              push(@result, '<dt>' . &inline($1, const => \%const) . '</dt>', '<dd>' . &inline($2, const => \%const) . '</dd>');
562                  if ($colspan[$i]) {          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
563                      while ($i + $colspan[$i] < @value and $value[$i + $colspan[$i]] eq '==') {              &back_push('blockquote', length($1), \@saved, \@result);
564                          $colspan[$i]++;              push @result, "<p>";
565                      }              push(@result, &inline($2, const => \%const));
566                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';              unshift @saved, "</p>";
567                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i]));          } elsif (/^\s*$/) {
568                  } else {              push(@result, splice(@saved));
569                      $value[$i] = '';              push(@result, "<p>");
570                  }              unshift(@saved, "</p>");
571              }          } elsif (/^(\s+.*)$/) {
572              push(@result, join('', '<tr>', @value, '</tr>'));              &back_push('pre', 1, \@saved, \@result);
573              # XXXXX              push(@result, &inline($1, const => \%const));
574              #######          } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
575          } else {              &back_push('table', 1, \@saved, \@result);
576              push(@result, &inline($_));              #######
577          }              # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.
578      }              # XXXXX
579      push(@result, splice(@saved));              my $tmp = "$1,";
580                my @value = map {/^"(.*)"$/ ? scalar($_ = $1, s/""/"/g, $_) : $_} ($tmp =~ /("[^"]*(?:""[^"]*)*"|[^,]*),/g);
581      if ($option{toc}) {              my @align = map {(s/^\s+//) ? ((s/\s+$//) ? ' align="center"' : ' align="right"') : ''} @value;
582          # Convert @toc (table of contents) to HTML.              my @colspan = map {($_ eq '==') ? 0 : 1} @value;
583          # This part is taken from Makio Tsukamoto's WalWiki.              for (my $i = 0; $i < @value; $i++) {
584          my (@tocsaved, @tocresult);                  if ($colspan[$i]) {
585          foreach (@toc) {                      while ($i + $colspan[$i] < @value and $value[$i + $colspan[$i]] eq '==') {
586              if (/^(-{1,3})(.*)/) {                          $colspan[$i]++;
587                  &back_push('ul', length($1), \@tocsaved, \@tocresult);                      }
588                  push(@tocresult, '<li>' . $2 . '</li>');                      $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
589              }                      $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], const => \%const));
590          }                  } else {
591          push(@tocresult, splice(@tocsaved));                      $value[$i] = '';
592          return join("\n", @tocresult, @result);                  }
593      } else {              }
594          return join("\n", @result);              push(@result, join('', '<tr>', @value, '</tr>'));
595      }              # XXXXX
596  }              #######
597            } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
598  sub back_push {              push @result, splice (@saved), '<'.lc($1).'>';
599      my ($tag, $level, $savedref, $resultref, $attr) = @_;              unshift @saved, "</p>";
600      while (@$savedref > $level) {              push @result, "<p>";
601          push(@$resultref, shift(@$savedref));          } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
602      }              push @result, splice (@saved), '</'.lc($1).'>';
603      if ($savedref->[0] ne "</$tag>") {          } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
604          push(@$resultref, splice(@$savedref));            my $num = 0+$1;
605      }            push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
606      while (@$savedref < $level) {            push @result, &inline ($2, const => \%const);
607          unshift(@$savedref, "</$tag>");          } else {
608          push(@$resultref, "<$tag$attr>");              push(@result, &inline($_, const => \%const));
609      }          }
610  }      }
611        push(@result, splice(@saved));
612  sub inline {      
613      my ($line) = @_;      my $toc = '';
614      $line = &escape($line);      if ($option{toc}) {
615      $line =~ s|'''([^']+?)'''|<i>$1</i>|g;  # Italic          # Convert @toc (table of contents) to HTML.
616      $line =~ s|''([^']+?)''|<b>$1</b>|g;    # Bold          # This part is taken from Makio Tsukamoto's WalWiki.
617      $line =~ s|(\d\d\d\d-\d\d-\d\d \(\w\w\w\) \d\d:\d\d:\d\d)|<span class="date">$1</span>|g;   # Date          my (@tocsaved, @tocresult);
618      $line =~ s!          foreach (@toc,@toc2) {
619                  (              if (/^(-{1,6})(.*)$/) {
620                      ((mailto|http|https|ftp):([^\x00-\x20()<>\x7F-\xFF])*)  # Direct http://...                  &back_push('ul', length($1), \@tocsaved, \@tocresult);
621                          |                  push(@tocresult, '<li>' . $2 . '</li>');
622                      ($bracket_name)             # [[likethis]], [[#comment]], [[Friend:remotelink]]              }
623                          |          }
624                      ($interwiki_definition)     # [[Friend http://somewhere/?q=sjis($1)]]          push(@tocresult, splice(@tocsaved));
625                          |          $toc = join("\n", @tocresult);
626                      ($wiki_name)                # LocalLinkLikeThis          $toc = $toc ? qq(<div id="wikipage-toc">$toc</div>) : '';
627                  )      }
628              !      $toc .= join("\n", @result);
629                  &make_link($1)      $toc =~ s#<p>\n</p>##g;
630              !gex;      $toc =~ s#[\x0D\x0A]+</#</#g;
631      return $line;      $toc =~ s#<pre>\n#<pre>#g;
632  }      $toc;
633    }
634  sub make_link {  
635      my $chunk = shift;  sub back_push {
636      # Walrus add (3) start      my ($tag, $level, $savedref, $resultref, $attr) = @_;
637      my $name  = $chunk;      while (@$savedref > $level) {
638      if ($chunk =~ /^\[\[([^ ]+?) ([^ ]+?)\]\]$/ and $form{mypage} ne $InterWikiName) {          push(@$resultref, shift(@$savedref));
639          ($name, $chunk) = ($1, $2);      }
640      } elsif ($chunk =~ /^mailto:(.*)$/) {      if ($savedref->[0] ne "</$tag>") {
641          $name = $1;          push(@$resultref, splice(@$savedref));
642      }      }
643      if ($use_autoimg and $name =~ /^(http|https|ftp|):.+\.(png|gif|jpe?g)/) {      while (@$savedref < $level) {
644          $name = qq(<img src="$name">) ;          unshift(@$savedref, "</$tag>");
645      }          push(@$resultref, "<$tag$attr>");
646      $name = &unarmor_name($name);      }
647      # Walrus add (3) end  }
648      if ($chunk =~ /^(http|https|ftp):/) {  
649          # Walrus mod (3) start  sub inline ($;%) {
650  #       if ($use_autoimg and $chunk =~ /\.(gif|png|jpeg|jpg)$/) {      my ($line, %option) = @_;
651  #           return qq(<a href="$chunk"><img src="$chunk"></a>);      $line = &escape($line);
652  #       } else {      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4)}ge;
653  #           return qq(<a href="$chunk">$chunk</a>);      $line =~ s{\[(INS|DEL|SUP|SUB|VAR|CODE|KBD|SAMP|DFN)(?:\(([A-Za-z0-9\x20-]+)\))?\[(.+?)\]\]}{<@{[lc $1]}@{[$2 ? qq( class="$2") : '']}>$3</@{[lc $1]}>}g;
654  #       }      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
655          return qq(<a href="$chunk">$name</a>);      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
656          # Walrus mod (3) end      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><ruby class="rb"><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby><span class="rp"> (</span><span class="rt-below">$3</span><span class="rp">) </span></span>:g;
657      } elsif ($chunk =~ /^(mailto):(.*)/) {      $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
658  #       return qq(<a href="$chunk">$2</a>);                 # Walrus del (3)      $line =~ s:\[RUBYB\[([^]]+)\] \[([^]]+)\]\]:<span class="ruby"><span class="rb">$1</span><span class="rp"> (</span><span class="rt-below">$2</span><span class="rp">) </span></span>:g;
659          return qq(<a href="$chunk">$name</a>);              # Walrus add (3)      $line =~ s%\[Q\[([^]]+)\](?: \[&lt;([\x21-\x5A\x5E-\x7E]+)&gt;\])?\]%。ヨ<q@{[$2?qq( cite="$2"):'']}>$1</q>。ラ%g;
660      } elsif ($chunk =~ /^$interwiki_definition$/) {      $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
661  #       return qq(<span class="InterWiki">$chunk</span>);   # Walrus del (3)      $line =~ s|''([^']+)''|<em>$1</em>|g;
662          return qq(<span class="InterWiki">$name</span>);    # Walrus add (3)      $line =~ s{
663      } elsif ($chunk =~ /^$embedded_name$/) {        (\[\[(\#\S+?)\]\])
664          return &embedded_to_html($chunk);        |\[\[([^[]+?)](?:&gt;&gt;([0-9]+))?]
665      } else {        |&gt;&gt;([0-9]+)
666          $chunk = &unarmor_name($chunk);        |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
667          $chunk = &unescape($chunk); # To treat '&' or '>' or '<' correctly.      }{
668          my $cookedchunk = &encode($chunk);        my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
669          if ($chunk =~ /^$interwiki_name$/) {        if ($l) {
670              my ($intername, $localname) = ($1, $2);          return &embedded_to_html($1);
671              my $remoteurl = $interwiki{$intername};        } elsif (defined $page) {
672              if ($remoteurl) {          &make_wikilink ($page, anchor => 0+$anchor);
673  #               $remoteurl =~ s/\b(euc|sjis|ykwk|asis)\(\$1\)/&interwiki_convert($1, $localname)/e;      # Walrus del (4)        } elsif ($anum) {
674                  $remoteurl =~ s/\b(euc|sjis|ykwk|asis|isbn)\(\$1\)/&interwiki_convert($1, $localname)/e; # Walrus add (4)          qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
675  #               return qq(<a href="$remoteurl">$chunk</a>); # Walrus del (3)        } elsif ($uri) {
676                  return qq(<a href="$remoteurl">$name</a>);  # Walrus add (3)          &make_urilink ($uri);
677              } else {        }
678  #               return $chunk;                              # Walrus del (3)      }gex;
679                  return $name;                               # Walrus add (3)      return $line;
680              }  }
681          } elsif ($database{$chunk}) {  
682              my $subject = &escape(&get_subjectline($chunk, delimiter => ''));  sub make_wikilink ($%) {
683  #           return qq(<a title="$subject" href="$url_cgi?$cookedchunk">$chunk</a>);  # Walrus del (3)    my ($ename, %option) = @_;
684              return qq(<a title="$subject" href="$url_cgi?$cookedchunk">$name</a>);   # Walrus add (3)    my $name = &unescape ($ename);
685          } elsif ($page_command{$chunk}) {    if ($database{$name}) {
686  #           return qq(<a title="$chunk" href="$url_cgi?$cookedchunk">$chunk</a>);    # Walrus del (3)      my $subject = &escape (&get_subjectline ($name, delimiter => ''));
687              return qq(<a title="$chunk" href="$url_cgi?$cookedchunk">$name</a>);     # Walrus add (3)      if ($option{anchor}) {
688          } else {        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
689  #           return qq($chunk<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit&amp;mypage=$cookedchunk">$editchar</a>); # Walrus del (3)      } else {
690              return qq($name<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit&amp;mypage=$cookedchunk">$editchar</a>);  # Walrus add (3)        return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}" class="wiki">$ename</a>);
691          }      }
692      }    } else {
693  }      return qq(<a title="@{[&Resource('JumpAndEditWikiPage',escape=>1)]}" href="$url_cgi?@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">@{[&Resource('JumpAndEditWikiPageMark',escape=>1)]}</span></a>);
694      }
695  # Walrus add (6) start  }
696  sub is_ignore_html {  
697      my ($pagename) = @_;  sub make_urilink ($;%) {
698      foreach (@ignore_html_page) {    require URI;
699          return 1 if ($pagename eq $_);    my $uri = shift;
700      }    if ($uri =~ s/^IW://) {       ## InterWiki (not URI)
701      return 0;      $uri = &unescape ($uri);
702  }      if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
703  # Walrus add (6) end        my ($site, $name) = ($1, $2);
704          for ($site, $name) {
705  # Walrus add (6) start          if (s/^"//) { s/"$//; s/\\(.)/$1/g }
706  sub html_to_ignored_html {        }
707      my $str = shift(@_);        &init_InterWikiName () unless $interwiki{'[[]]'};
708      my $text_regex        = q{[^<]*};        if ($interwiki{$site}) {
709      my $tag_regex_        = q{[^"'<>]*(?:"[^"]*"[^"'<>]*|'[^']*'[^"'<>]*)*(?:>|(?=<)|$(?!\n))}; #'}}}}          &load_formatter ('interwiki');
710      my $comment_tag_regex = '<!(?:--[^-]*-(?:[^-]+-)*?-(?:[^>-]*(?:-[^>-]+)*?)??)*(?:>|$(?!\n)|--.*$)';          my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
711      my $tag_regex         = qq{$comment_tag_regex|<$tag_regex_};          $site = &escape ($site); $name = &escape ($name);
712      my $ignored           = join('|', @ignore_html_tags);          qq(&lt;<a href="$uri" class="out-of-wiki interwiki" title="$name ($site); URI: &lt;$uri&gt;"><span class="interwiki-site">$site:</span><span class="interwiki-name">$name</span></a>&gt;);
713      my $result = '';        } else {
714      while ($str =~ /($text_regex)($tag_regex)?/gso) {          qq(&lt;@{[&Resource('Error:UnknownInterWikiName=',escape=>1)]}@{[&escape ($site)]}&gt;);
715        last if $1 eq '' and $2 eq '';        }
716        $result .= $1;      } else {
717        my $tag_tmp = $2;        qq(&lt;@{[&Resource('Error:InvalidInterWiki=',escape=>1)]}@{[&escape($uri)]}&gt;);
718        $result .= ($tag_tmp =~ /^<\/?($ignored)(?![0-9A-Za-z])/i) ? $tag_tmp : &escape($tag_tmp);      }
719        if ($tag_tmp =~ /^<(XMP|PLAINTEXT|SCRIPT)(?![0-9A-Za-z])/i) {    } elsif ($uri =~ /^urn:/) {   ## URN
720          $str =~ /(.*?)(?:<\/$1(?![0-9A-Za-z])$tag_regex_|$)/gsi;      my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
721          $result .= &escape($1);      qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
722        }    } elsif ($uri =~ s/^MAIL://) {        ## mail address (not URI)
723      }      my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
724      return $result;      qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
725  }    } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) {   ## image (not URI itself)
726  # Walrus add (6) end      my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
727        qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
728  sub print_message {    } else {      ## misc. URI
729      my ($msg) = @_;      CGI::Carp::warningsToBrowser (0);
730      print qq(<p><strong>$msg</strong></p>);      my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
731  }      CGI::Carp::warningsToBrowser (1);
732        qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
733  sub init_form {    }
734      if (param()) {  }
735          foreach my $var (param()) {  
736              $form{$var} = param($var);  {my $FormIndex = 0;
737          }  sub make_custom_form ($$$$) {
738      } else {      my ($wfname, $definition, $template, $option) = @_;
739          $ENV{QUERY_STRING} = $FrontPage;      ## $template and $option is currently not used in this procedure.
740      }      unless ($main::_EMBEDED) {
741            $FormIndex++;
742      my $query = &decode($ENV{QUERY_STRING});          if (length $definition) {
743      if ($page_command{$query}) {              my $param = bless {}, 'SuikaWiki::Plugin';
744          $form{mycmd} = $page_command{$query};              my $lastmodified = &get_info($form{mypage}, $info_LastModified);
745          $form{mypage} = $query;              &load_formatter (qw/form_input form_option/);
746      } elsif ($query =~ /^($wiki_name)$/) {              $definition = &unescape ($definition);
747          $form{mycmd} = 'read';              $definition =~ s/\\(.)/$1/g;
748          $form{mypage} = $1;              $option = &unescape ($option);
749      } elsif ($database{$query}) {              $option =~ s/\\(.)/$1/g;
750          $form{mycmd} = 'read';              $fmt{form_option}->replace ($option, $param);
751          $form{mypage} = $query;              $param->{output}->{form} = 1 unless defined $param->{output}->{form};
752      }              $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
753                my $target_page = $param->{output}->{page} || $form{mypage};
754      # mypreview_edit        -> do_edit, with preview.              $param->{form_disabled} = 1 if $fixedpage{$target_page};
755      # mypreview_adminedit   -> do_adminedit, with preview.              my $target_form = $param->{output}->{id};
756      # mypreview_write       -> do_write, without preview.              my $r = '';
757      foreach (keys %form) {              $r = <<EOH if $param->{output}->{form};
758          if (/^mypreview_(.*)$/) {  <form method="post" action="$url_cgi" id="wikiform-$FormIndex" class="wikiform">
759              $form{mycmd} = $1;    <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'read':'wikiform']}">
760              $form{mypreview} = 1;    <input type="hidden" name="mypage" value="@{[&escape($target_page)]}">
761          }    <input type="hidden" name="myLastModified" value="$lastmodified">
762      }    <input type="hidden" name="mytouch" value="on">
763      <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex)]}">
764      #  EOH
765      # $form{mycmd} is frozen here.              $r .= qq(<a name="wikiform-$FormIndex"></a>) if $UA =~ m#Mozilla/[12]\.#;
766      #              $r .= $fmt{form_input}->replace ($definition, $param);
767                $r .= "</form>\n" if $param->{output}->{form};
768      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);              $r;
769      $form{myname} = &code_convert(\$form{myname}, $kanjicode);         } else {  ## No input-interface WikiForm
770  }             qq(<a id="wikiform-$FormIndex" name="wikiform-$FormIndex"><!-- #form --></a>);
771           }
772  sub update_recent_changes {      } else {
773      my $update = "- @{[&get_now]} @{[&armor_name($form{mypage})]} @{[&get_subjectline($form{mypage})]}";          qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
774      my @oldupdates = split(/\r?\n/, $database{$RecentChanges});      }
775      my @updates;  }}
776      foreach (@oldupdates) {  
777          /^\- \d\d\d\d\-\d\d\-\d\d \(...\) \d\d:\d\d:\d\d (\S+)/;    # date format.  sub print_message {
778          my $name = &unarmor_name($1);      my ($msg) = @_;
779          if (&is_exist_page($name) and ($name ne $form{mypage})) {      print qq(<p><strong>@{[&escape($msg)]}</strong></p>);
780              push(@updates, $_);  }
781          }  
782      }  sub init_form {
783      if (&is_exist_page($form{mypage})) {      ## TODO: Support multipart/form-data
784          unshift(@updates, $update);      my $query = '';
785      }      if (uc $main::ENV{REQUEST_METHOD} eq 'POST') {
786      splice(@updates, $maxrecent + 1);        read STDIN, $query, $main::ENV{CONTENT_LENGTH};
787      $database{$RecentChanges} = join("\n", @updates);      }
788      if ($file_touch) {      $query .= ($query ? ';' : '') . $main::ENV{QUERY_STRING};
789          open(FILE, "> $file_touch");      if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
790          print FILE localtime() . "\n";        my $query = &decode($main::ENV{QUERY_STRING});
791          close(FILE);        $query = &code_convert(\$query, $kanjicode);
792      }        if ($page_command{$query}) {
793  }          $form{mycmd} = $page_command{$query};
794            $form{mypage} = $query;
795  sub get_subjectline {        } else {
796      my ($page, %option) = @_;          $form{mypage} = $query;
797      if (not &is_editable($page)) {          $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';
798          return "";        }
799      } else {      } else {
800          # Delimiter check.        for (split /[;&]/, $query) {
801          my $delim = $subject_delimiter;          if (my ($n, $v) = split /=/, $_, 2) {
802          if (defined($option{delimiter})) {            for ($n, $v) {tr/+/ /; s/%([0-9A-Fa-f][0-9A-Fa-f])/pack 'C', hex $1/ge};
803              $delim = $option{delimiter};            $form{$n} = $v;
804          }          }
805          }
806          # Get the subject of the page.        unless (defined $form{mypage}) {
807          my $subject = $database{$page};          $form{mypage} = $form{epage};
808          $subject =~ s/\r?\n.*//s;          $form{mypage} =~ s/([0-9A-F]{2})/ord hex $1/g;
809          return "$delim$subject";        }
810      }        if ($page_command{$form{mypage}} && $form{mycmd} eq 'read') {
811  }          $form{mypage} = &code_convert(\$form{mypage}, $kanjicode);
812            $form{mycmd} = $page_command{$form{mypage}};
813  sub send_mail_to_admin {        }
814      my ($page, $mode) = @_;      }
815      return unless $modifier_sendmail;      $form{mypage} ||= 'HomePage';
816      my $message = <<"EOD";      $form{mycmd} ||= 'read';
817  To: $modifier_mail  
818  From: $modifier_mail      # mypreview_edit        -> do_edit, with preview.
819  Subject: [Wiki]      # mypreview_adminedit   -> do_adminedit, with preview.
820  MIME-Version: 1.0      # mypreview_write       -> do_write, without preview.
821  Content-Type: text/plain; charset=ISO-2022-JP      foreach (keys %form) {
822  Content-Transfer-Encoding: 7bit          if (/^mypreview_(.*)$/) {
823                $form{mycmd} = $1;
824  --------              $form{mypreview} = 1;
825  MODE = $mode          }
826  REMOTE_ADDR = $ENV{REMOTE_ADDR}      }
827  REMOTE_HOST = $ENV{REMOTE_HOST}  
828  --------      #
829  $page      # $form{mycmd} is frozen here.
830  --------      #
831  $database{$page}  
832  --------      for (grep /^wikiform__/, keys %form) {
833  EOD          $form{$_} = &code_convert (\$form{$_}, $kanjicode);
834      &code_convert(\$message, 'jis');      }
835      open(MAIL, "| $modifier_sendmail");      $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
836      print MAIL $message;      $form{myname} = &code_convert(\$form{myname}, $kanjicode);
837      close(MAIL);  }
838  }  
839    sub update_recent_changes {
840  sub open_db {      my $update = "- @{[&get_now]} [[$form{mypage}]] @{[&get_subjectline($form{mypage})]}";
841      if ($modifier_dbtype eq 'dbmopen') {      my @oldupdates = split(/\x0D?\x0A/, $database{RecentChanges});
842          dbmopen(%database, $dataname, 0666) or &print_error("(dbmopen) $dataname");      shift @oldupdates; ## '#?' magic line
843          dbmopen(%infobase, $infoname, 0666) or &print_error("(dbmopen) $infoname");      my @updates;
844      } elsif ($modifier_dbtype eq 'AnyDBM_File') {      foreach (@oldupdates) {
845          tie(%database, "AnyDBM_File", $dataname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $dataname");          /^\- \d\d\d\d\-\d\d\-\d\d \d\d:\d\d \[\[([^]]+)\]\]/;
846          tie(%infobase, "AnyDBM_File", $infoname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $infoname");          my $name = $1;
847      } else {          if ($name ne $form{mypage}) {
848          tie(%database, "Yuki::YukiWikiDB", $dataname) or &print_error("(tie Yuki::YukiWikiDB) $dataname");              push @updates, $_;
849          tie(%infobase, "Yuki::YukiWikiDB", $infoname) or &print_error("(tie Yuki::YukiWikiDB) $infoname");          }
850      }      }
851  }      if (&is_exist_page($form{mypage})) {
852          unshift @updates, $update;
853  sub close_db {      }
854      if ($modifier_dbtype eq 'dbmopen') {      splice @updates, (&Resource ('RecentChanges:Max') || 50) + 1;
855          dbmclose(%database);      $database{RecentChanges} = "#?SuikaWiki/0.9\n" . join("\n", @updates);
856          dbmclose(%infobase);      if ($PathTo{TouchFile}) {
857      } elsif ($modifier_dbtype eq 'AnyDBM_File') {          open(FILE, "> ".$PathTo{TouchFile});
858          untie(%database);          print FILE localtime() . "\n";
859          untie(%infobase);          close(FILE);
860      } else {      }
861          untie(%database);  }
862          untie(%infobase);  
863      }  {my %SubjectLine;
864  }  sub get_subjectline {
865        my ($page, %option) = @_;
866  sub open_diff {      unless (defined $SubjectLine{$page}) {
867      if ($modifier_dbtype eq 'dbmopen') {        if (not &is_editable($page)) {
868          dbmopen(%diffbase, $diffname, 0666) or &print_error("(dbmopen) $diffname");          $SubjectLine{$page} = "";
869      } elsif ($modifier_dbtype eq 'AnyDBM_File') {        } else {
870          tie(%diffbase, "AnyDBM_File", $diffname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $diffname");          $SubjectLine{$page} = $database{$page};
871      } else {          $SubjectLine{$page} =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
872          tie(%diffbase, "Yuki::YukiWikiDB", $diffname) or &print_error("(tie Yuki::YukiWikiDB) $diffname");          $SubjectLine{$page} =~ s/\x0D?\x0A.*//s;
873      }        }
874  }      }
875        if (length $SubjectLine{$page}) {
876  sub close_diff {        $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
877      if ($modifier_dbtype eq 'dbmopen') {        $option{delimiter}.$SubjectLine{$page}.$option{tail};
878          dbmclose(%diffbase);      } else {
879      } elsif ($modifier_dbtype eq 'AnyDBM_File') {        '';
880          untie(%diffbase);      }
881      } else {  }}
882          untie(%diffbase);  
883      }  sub open_db {
884  }      if ($modifier_dbtype eq 'dbmopen') {
885            dbmopen(%database, $PathTo{WikiDataBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDataBase}");
886  sub print_searchform {          dbmopen(%infobase, $PathTo{WikiInfoBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiInfoBase}");
887      my ($word) = @_;      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
888      print <<"EOD";          eval q{use AnyDBM_File};
889  <form action="$url_cgi" method="get">          tie(%database, "AnyDBM_File", $PathTo{WikiDataBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDataBase}");
890      <input type="hidden" name="mycmd" value="search">          tie(%infobase, "AnyDBM_File", $PathTo{WikiInfoBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiInfoBase}");
891      <input type="text" name="mymsg" value="$word" size="20">      } else {
892      <input type="submit" value="$resource{searchbutton}">          eval q{use Yuki::YukiWikiDB};
893  </form>          tie(%database, "Yuki::YukiWikiDB", $PathTo{WikiDataBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDataBase}");
894  EOD          tie(%infobase, "Yuki::YukiWikiDB", $PathTo{WikiInfoBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiInfoBase}");
895  }      }
896    }
897  sub print_editform {  
898      my ($mymsg, $lastmodified, %mode) = @_;  sub close_db {
899      my $frozen = &is_frozen($form{mypage});      if ($modifier_dbtype eq 'dbmopen') {
900            dbmclose(%database);
901      if ($form{mypreview}) {          dbmclose(%infobase);
902          if ($form{mymsg}) {      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
903              unless ($mode{conflict}) {          untie(%database);
904                  print qq(<h3>$resource{previewtitle}</h3>\n);          untie(%infobase);
905                  print qq($resource{previewnotice}\n);      } else {
906                  print qq(<div class="preview">\n);          untie(%database);
907                  &print_content($form{mymsg});          untie(%infobase);
908                  print qq(</div>\n);      }
909              }  }
910          } else {  
911              print qq($resource{previewempty});  sub open_diff {
912          }      if ($modifier_dbtype eq 'dbmopen') {
913          $mymsg = &escape($form{mymsg});          dbmopen(%diffbase, $PathTo{WikiDiffBase}, 0666) or &print_error("(dbmopen) $PathTo{WikiDiffBase}");
914      } else {      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
915          $mymsg = &escape($mymsg);          tie(%diffbase, "AnyDBM_File", $PathTo{WikiDiffBase}, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $PathTo{WikiDiffBase}");
916      }      } else {
917            tie(%diffbase, "Yuki::YukiWikiDB", $PathTo{WikiDiffBase}) or &print_error("(tie Yuki::YukiWikiDB) $PathTo{WikiDiffBase}");
918      my $edit = $mode{admin} ? 'adminedit' : 'edit';      }
919    }
920      print <<"EOD";  
921  <form action="$url_cgi" method="post">  sub close_diff {
922      @{[ $mode{admin} ? qq($resource{frozenpassword} <input type="password" name="mypassword" value="$form{mypassword}" size="10"><br>) : "" ]}      if ($modifier_dbtype eq 'dbmopen') {
923      <input type="hidden" name="myLastModified" value="$lastmodified">          dbmclose(%diffbase);
924      <input type="hidden" name="mypage" value="$form{mypage}">      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
925      <textarea cols="$cols" rows="$rows" name="mymsg" wrap="off">$mymsg</textarea><br>          untie(%diffbase);
926  @{[      } else {
927      $mode{admin} ?          untie(%diffbase);
928      qq(      }
929      <input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>$resource{frozenbutton}  }
930      <input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>$resource{notfrozenbutton}<br>)  
931      : ""  sub print_editform {
932  ]}      my ($mymsg, $lastmodified, %mode) = @_;
933  @{[      my $frozen = &is_frozen($form{mypage});
934      $mode{conflict} ? "" :  
935      qq(      if ($form{mypreview}) {
936          <input type="checkbox" name="mytouch" value="on" checked="checked">$resource{touch}<br>          if ($form{mymsg}) {
937          <input type="submit" name="mypreview_$edit" value="$resource{previewbutton}">              unless ($mode{conflict}) {
938          <input type="submit" name="mypreview_write" value="$resource{savebutton}"><br>                  print qq(<h3>@{[&Resource('Preview:Title',escape=>1)]}</h3>\n);
939      )                  print qq(<p>@{[&Resource('Preview:Notice',escape=>1)]}</p>\n);
940  ]}                  print qq(<div class="preview">\n);
941  </form>                  &print_content($form{mymsg});
942  EOD                  print qq(</div>\n);
943      unless ($mode{conflict}) {              }
944          # Show the format rule.          } else {
945          open(FILE, $file_format) or &print_error("($file_format)");              print @{[&Resource('Preview:Empty',escape=>1)]};
946          my $content = join('', <FILE>);          }
947          &code_convert(\$content, $kanjicode);          $mymsg = &escape($form{mymsg});
948          close(FILE);      } else {
949          print &text_to_html($content, toc=>0);          $mymsg = &escape($mymsg || $database{NewPageTemplate});
950      }      }
951  }      my $magic = '';
952        $magic = $1 if $mymsg =~ m/^([^\x0A\x0D]+)/s;
953  sub print_passwordform {  
954          print <<"EOD";      my $edit = $mode{admin} ? 'adminedit' : 'edit';
955  <form action="$url_cgi" method="post">      my $escapedmypage = &escape($form{mypage});
956      <input type="hidden" name="mycmd" value="adminchangepassword">      my $escapedmypassword = &escape($form{mypassword});
957      $resource{oldpassword} <input type="password" name="myoldpassword" size="10"><br>      my $selected = 'read';
958      $resource{newpassword} <input type="password" name="mynewpassword" size="10"><br>      if ($form{after_edit_cmd}) {
959      $resource{newpassword2} <input type="password" name="mynewpassword2" size="10"><br>          $selected = $form{after_edit_cmd};
960      <input type="submit" value="$resource{changepasswordbutton}"><br>      } elsif ($magic =~ /Const|Config|CSS/) {
961  </form>          $selected = 'edit';
962  EOD      }
963  }      my $afteredit = <<EOH;
964    <select name="after_edit_cmd">
965  sub is_editable {  <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
966      my ($page) = @_;  <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
967      if (&is_bracket_name($page)) {  </select>
968          return 0;  EOH
969      } elsif ($fixedpage{$page}) {  
970          return 0;      print <<"EOD";
971      } elsif ($page =~ /\s/) {  <form action="$url_cgi" method="post">
972          return 0;  <h2>@{[&Resource('Edit:Title',escape=>1)]}</h2>
973      } elsif ($page =~ /^\#/) {      @{[ $mode{conflict} ? '' : qq(<input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}"><kbd>S</kbd>) ]}
974          return 0;      @{[ $mode{admin} ? qq(<label>@{[&Resource('Edit:Password=',escape=>1)]}<input type="password" name="mypassword" value="$escapedmypassword" size="10"></label>) : "" ]} [@{[do {my $n = 0;
975      } elsif ($page =~ /^$interwiki_name$/) {                 $mymsg =~ s/(?:-+\s)?\[([0-9]+)\]/$n = $1 if $1 > $n; $&/mge;
976          return 0;                 ++$n}]}]<br>
977      } else {      <input type="hidden" name="myLastModified" value="$lastmodified">
978          return 1;      <input type="hidden" name="mypage" value="$escapedmypage">
979      }      <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">$mymsg</textarea><br>
980  }  @{[
981        $mode{admin} ?
982  # armor_name:      qq(
983  #   WikiName -> WikiName      <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>@{[&Resource('Edit:Freeze',escape=>1)]}</label>
984  #   not_wiki_name -> [[not_wiki_name]]      <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br>)
985  sub armor_name {      : ""
986      my ($name) = @_;  ]}
987      if ($name =~ /^$wiki_name$/) {  @{[
988          return $name;      $mode{conflict} ? "" :
989      } else {      qq(
990          return "[[$name]]";          <input type="checkbox" name="mytouch" value="on" checked="checked">@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}<br>
991      }          <input type="submit" name="mypreview_$edit" value="@{[&Resource('Edit:Preview',escape=>1)]}">
992  }          <input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S"><kbd>S</kbd>
993           $afteredit
994  # unarmor_name:         <br>
995  #   [[bracket_name]] -> bracket_name      )
996  #   WikiName -> WikiName  ]}
997  sub unarmor_name {  </form>
998      my ($name) = @_;  EOD
999      if ($name =~ /^$bracket_name$/) {      unless ($mode{conflict}) {
1000          return $1;          ## Show help text
1001      } else {          my $help = $database{WikiEditHelp};
1002          return $name;          $help =~ s!^\#\?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1003      }          print &text_to_html ($help, toc => 0);
1004  }      }
1005    }
1006  sub is_bracket_name {  
1007      my ($name) = @_;  sub print_passwordform {
1008      if ($name =~ /^$bracket_name$/) {          print <<"EOD";
1009          return 1;  <form action="$url_cgi" method="post">
1010      } else {      <input type="hidden" name="mycmd" value="adminchangepassword">
1011          return 0;      <label>@{[&Resource('Password:Old=',escape=>1)]}<input type="password" name="myoldpassword" size="10"></label><br>
1012      }      <label>@{[&Resource('Password:New1=',escape=>1)]}<input type="password" name="mynewpassword" size="10"></label><br>
1013  }      <label>@{[&Resource('Password:New2=',escape=>1)]}<input type="password" name="mynewpassword2" size="10"></label><br>
1014        <input type="submit" value="@{[&Resource('WikiForm:Change',escape=>1)]}"><br>
1015  sub decode {  </form>
1016      my ($s) = @_;  EOD
1017      $s =~ tr/+/ /;  }
1018      $s =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;  
1019      return $s;  sub is_editable {
1020  }      my ($page) = @_;
1021        if ($fixedpage{$page} || $page =~ /\s/ || $page =~ /^\#/) {
1022  sub encode {          return 0;
1023      my ($s) = @_;      } else {
1024      my $encoded = '';          return 1;
1025      foreach my $ch (split(//, $s)) {      }
1026          if ($ch =~ /[A-Za-z0-9_]/) {  }
1027              $encoded .= $ch;  
1028          } else {  # armor_name:
1029              $encoded .= '%' . sprintf("%02X", ord($ch));  #   WikiName -> WikiName
1030          }  #   not_wiki_name -> [[not_wiki_name]]
1031      }  sub armor_name { qq([[$_[0]]]) }
1032      return $encoded;  
1033  }  # unarmor_name:
1034    #   [[bracket_name]] -> bracket_name
1035  sub init_resource {  #   WikiName -> WikiName
1036      open(FILE, $file_resource) or &print_error("(resource)");  sub unarmor_name {
1037      while (<FILE>) {      my ($name) = @_;
1038          chomp;      if ($name =~ /^\[\[(\S+?)\]\]$/) {
1039          next if /^#/;          return $1;
1040          my ($key, $value) = split(/=/, $_, 2);      } else {
1041          $resource{$key} = &code_convert(\$value, $kanjicode);          return $name;
1042      }      }
1043      close(FILE);  }
1044  }  
1045    sub decode {
1046  sub conflict {      my ($s) = @_;
1047      my ($page, $rawmsg) = @_;      $s =~ tr/+/ /;
1048      if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {      $s =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;
1049          return 0;      return $s;
1050      }  }
1051      open(FILE, $file_conflict) or &print_error("(conflict)");  
1052      my $content = join('', <FILE>);  sub encode {
1053      &code_convert(\$content, $kanjicode);      my ($s) = @_;
1054      close(FILE);      my $encoded = '';
1055      &print_header($page);      foreach my $ch (split(//, $s)) {
1056      &print_content($content);          if ($ch =~ /[A-Za-z0-9_]/) {
1057      &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);              $encoded .= $ch;
1058      &print_footer($page);          } else {
1059      return 1;              $encoded .= '%' . sprintf("%02X", ord($ch));
1060  }          }
1061        }
1062  sub get_now {      return $encoded;
1063      my (@week) = qw(Sun Mon Tue Wed Thu Fri Sat);  }
1064      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);  
1065      $year += 1900;  sub conflict {
1066      $mon++;      my ($page, $rawmsg) = @_;
1067      $mon = "0$mon" if $mon < 10;      if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {
1068      $day = "0$day" if $day < 10;          return 0;
1069      $hour = "0$hour" if $hour < 10;      }
1070      $min = "0$min" if $min < 10;      &print_header($page, -noindex => 1);
1071      $sec = "0$sec" if $sec < 10;      &print_content(&Resource('Error:Conflict'));
1072      $weekday = $week[$weekday];      &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);
1073      return "$year-$mon-$day ($weekday) $hour:$min:$sec";      &print_footer($page);
1074  }      return 1;
1075    }
1076  # [[YukiWiki http://www.hyuki.com/yukiwiki/wiki.cgi?euc($1)]]  
1077  sub init_InterWikiName {  sub get_now {
1078      my $content = $database{$InterWikiName};      my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
1079      while ($content =~ /\[\[(\S+) +(\S+)\]\]/g) {      $year += 1900;
1080          my ($name, $url) = ($1, $2);      $mon++;
1081          $interwiki{$name} = $url;      $mon = "0$mon" if $mon < 10;
1082      }      $day = "0$day" if $day < 10;
1083  }      $hour = "0$hour" if $hour < 10;
1084        $min = "0$min" if $min < 10;
1085  sub interwiki_convert {      #$sec = "0$sec" if $sec < 10;
1086      my ($type, $localname) = @_;      return "$year-$mon-$day $hour:$min";
1087      if ($type eq 'sjis' or $type eq 'euc') {  }
1088          &code_convert(\$localname, $type);  
1089          return &encode($localname);  sub init_InterWikiName {
1090      } elsif ($type eq 'ykwk') {    my @content = split /\n/, $database{InterWikiName};
1091          # for YukiWiki1    for (@content) {
1092          if ($localname =~ /^$wiki_name$/) {      if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
1093              return $localname;        $interwiki{$1} = $2;
1094          } else {      }
1095              &code_convert(\$localname, 'sjis');    }
1096              return &encode("[[" . $localname . "]]");    $interwiki{'[[]]'} = 1;       ## dummy
1097          }  }
1098      } elsif ($type eq 'asis') {  
1099          return $localname;  
1100      # Walrus add (4) start  sub get_info {
1101      } elsif ($type eq 'isbn') {      my ($page, $key) = @_;
1102          $localname = join('', ($localname =~ /[0-9x]/g)) if ($localname =~ /^(\d-?){9}[\dx]$/);      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1103          return $localname;      return $info{$key};
1104      # Walrus add (4) end  }
1105      } else {  
1106          return $localname;  sub set_info {
1107      }      my ($page, $key, $value) = @_;
1108  }      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1109        $info{$key} = $value;
1110  sub get_info {      my $s = '';
1111      my ($page, $key) = @_;      for (keys %info) {
1112      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});          $s .= "$_=$info{$_}\n";
1113      return $info{$key};      }
1114  }      $infobase{$page} = $s;
1115    }
1116  sub set_info {  
1117      my ($page, $key, $value) = @_;  sub frozen_reject {
1118      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});      my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);
1119      $info{$key} = $value;      my ($willbefrozen) = $form{myfrozen};
1120      my $s = '';      if (not $isfrozen and not $willbefrozen) {
1121      for (keys %info) {          # You need no check.
1122          $s .= "$_=$info{$_}\n";          return 0;
1123      }      } elsif (valid_password($form{mypassword})) {
1124      $infobase{$page} = $s;          # You are admin.
1125  }          return 0;
1126        } else {
1127  sub frozen_reject {          &print_error(&Resource('Error:PasswordIsIncorrect'));
1128      my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);          return 1;
1129      my ($willbefrozen) = $form{myfrozen};      }
1130      if (not $isfrozen and not $willbefrozen) {  }
1131          # You need no check.  
1132          return 0;  sub valid_password {
1133      } elsif (valid_password($form{mypassword})) {      my ($givenpassword) = @_;
1134          # You are admin.      my ($validpassword_crypt) = &get_info($PageName{AdminSpecialPage}, 'AdminPassword');
1135          return 0;      if (crypt($givenpassword, $validpassword_crypt) eq $validpassword_crypt) {
1136      } else {          return 1;
1137          &print_error($resource{passworderror});      } else {
1138          return 1;          return 0;
1139      }      }
1140  }  }
1141    
1142  sub valid_password {  sub is_frozen {
1143      my ($givenpassword) = @_;      my ($page) = @_;
1144      my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_AdminPassword);      if (&get_info($page, $info_IsFrozen)) {
1145      if (crypt($givenpassword, $validpassword_crypt) eq $validpassword_crypt) {          return 1;
1146          return 1;      } else {
1147      } else {          return 0;
1148          return 0;      }
1149      }  }
1150  }  
1151    sub do_comment {
1152  sub is_frozen {      my ($content) = $database{$form{mypage}};
1153      my ($page) = @_;      my $default_name;   ## this code does not strict.
1154      if (&get_info($page, $info_IsFrozen)) {      $default_name = $1 if $content =~ /default-name="([^"]+)"/;
1155          return 1;      my $datestr = '[WEAK['.&get_now.']]';
1156      } else {      my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
1157          return 0;      ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
1158      }      if ($namestr =~ /^(?:>>)?[0-9]/) {
1159  }        $namestr = qq( ''$namestr'': );
1160        } elsif (length $namestr) {
1161  sub do_comment {        $namestr = qq( ''[[$namestr]]'': );
1162      my ($content) = $database{$form{mypage}};      }
1163      my $datestr = &get_now;      my $anchor = &get_new_anchor_index ($content);
1164      my $namestr = $form{myname} ? " ''[[$form{myname}]]'' : " : " ";      my $i = 1;  my $o = 0;
1165      if ($content =~ s/(\Q$embed_comment\E)/- $datestr$namestr$form{mymsg}\n$1/) {      $content =~ s{(\[\[\#r?comment\]\])}{
1166          ;        my $embed = $1;
1167      } else {        if ($i == $form{comment_index}) {
1168          $content =~ s/(\Q$embed_rcomment\E)/$1\n- $datestr$namestr$form{mymsg}/;          if ($embed ne '[[#rcomment]]') {
1169      }            $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;
1170      if ($form{mymsg}) {          } else {
1171          $form{mymsg} = $content;            $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;
1172          $form{mytouch} = 'on';          }
1173          &do_write;        }
1174      } else {        $i++; $embed;
1175          $form{mycmd} = 'read';      }ge;
1176          &do_read;      unless ($o) {
1177      }        $content = "#?SuikaWiki/0.9\n\n" unless $content;
1178  }        $content .= "\n" unless $content =~ /\n$/s;
1179          $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
1180  sub embedded_to_html {      }
1181      my ($embedded) = @_;      $form{__comment_anchor_index} = $anchor;
1182      if ($embedded eq $embed_comment or $embedded eq $embed_rcomment) {      if ($form{mymsg} || $form{myname}) {
1183          my $lastmodified = &get_info($form{mypage}, $info_LastModified);          $form{mymsg} = $content;
1184          return <<"EOD";          $form{mytouch} = 'on';
1185  <form action="$url_cgi" method="post">          &do_write;
1186      <input type="hidden" name="mycmd" value="comment">      } else {
1187      <input type="hidden" name="mypage" value="$form{mypage}">          $form{mycmd} = 'read';
1188      <input type="hidden" name="myLastModified" value="$lastmodified">          &do_read;
1189      <input type="hidden" name="mytouch" value="on">      }
1190      $resource{yourname}  }
1191      <input type="text" name="myname" value="" size="10">  
1192      <input type="text" name="mymsg" value="" size="40">  sub get_new_anchor_index ($) {
1193      <input type="submit" value="$resource{commentbutton}">      my $content = shift;
1194  </form>      my $anchor = 0;
1195  EOD      $content =~ s/^(?:[-=]+\s*)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
1196      # Walrus add (5) start      $anchor + 1;
1197      } elsif ($embedded =~ /$embed_interwiki/ and my $remoteurl = $interwiki{$2}) {  }
1198          $_ = &make_interwiki_box($1, $2);  
1199          return ($_) ? $_ : $embedded;  my $CommentIndex = 0;
1200      # Walrus add (5) end  sub embedded_to_html {
1201      } else {      my ($embedded) = @_;
1202          return $embedded;      if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
1203      }        unless ($main::_EMBEDED) {
1204  }          my $lastmodified = &get_info($form{mypage}, $info_LastModified);
1205            return <<"EOD";
1206  # Walrus add (5) start  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
1207  sub do_interwiki_box {      <input type="hidden" name="mycmd" value="comment">
1208      my $remoteurl = $interwiki{$form{'myintername'}};      <input type="hidden" name="mypage" value="$form{mypage}">
1209      if ($remoteurl) {      <input type="hidden" name="myLastModified" value="$lastmodified">
1210          $remoteurl =~ s/\b(euc|sjis|ykwk|asis|isbn)\(\$1\)/&interwiki_convert($1, $form{'mylocalname'})/e;      <input type="hidden" name="mytouch" value="on">
1211          print "Location: $remoteurl\n\n";      <input type="hidden" name="comment_index" value="$CommentIndex">
1212          exit(1);      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
1213      } else {      <input type="text" name="myname" value="" size="10" class="comment-name">
1214          &do_read;      <input type="text" name="mymsg" value="" size="60" class="comment-msg">
1215      }      <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit">
1216  }  </p></form>
1217  # Walrus add (5) end  EOD
1218         } else {
1219  # Walrus add (5) start          return <<"EOD";
1220  sub make_interwiki_box {  <del><form action="$url_cgi" method="get">
1221      my ($localname, $intername) = @_;      <input type="hidden" name="mycmd" value="read">
1222      my %ignoretype = (      <input type="hidden" name="mypage" value="$form{mypage}">
1223          'box'      => 'text',      @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
1224          'text'     => 'text',      <input type="text" name="myname" value="" size="10" disabled="disabled">
1225          'pass'     => 'password',      <input type="text" name="mymsg" value="" size="60" disabled="disabled">
1226          'password' => 'password'  </form></del>
1227      );  EOD
1228      my $converted = ($ignoretype{$localname}) ? <<EOD : undef;      }
1229  <form action="$url_cgi" method="post">    } elsif ($embedded =~ /$embed_command{searched}/) {
1230      <input type="hidden" name="mycmd" value="interwikibox">      return get_search_result ($1, -match_myself => 1);
1231      <input type="hidden" name="mypage" value="$form{mypage}">    } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
1232      <input type="hidden" name="myintername" value="$intername">      my ($name, $r) = ($1, '');
1233      $intername:      if ($main::_EMBEDED != 1) {
1234      <input type="$ignoretype{$localname}" name="mylocalname" value="" size="10">        my ($content, $cf) = ($database{$name}, 'SuikaWiki/0.9');
1235      <input type="submit" value="Submit">        $cf = $1 if $content =~ s!^(?:[\#<]\?|/\*\s*)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1236  </form>        if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
1237  EOD          $main::_EMBEDED = 1;
1238  }          $r = &text_to_html ($content, content_format => $cf);
1239  # Walrus add (5) end          $main::_EMBEDED = 0;
1240          } elsif (length $content) {
1241  sub code_convert {          $r = "<pre>@{[&escape ($content)]}</pre>";
1242      my ($contentref, $kanjicode) = @_;        } else {
1243  #   &Jcode::convert($contentref, $kanjicode);       # for Jcode.pm          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
1244      &jcode::convert($contentref, $kanjicode);       # for jcode.pl        }
1245      return $$contentref;      } else {    ## nested #EMBED
1246  }        $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
1247        }
1248  sub test_convert {      return qq(<blockquote title="@{[&escape($name)]}" class="wiki-embed">$r<div class="cite-note">。リ<cite><a href="$url_cgi?@{[&encode($name)]}" class="wiki">@{[&escape($name)]}</a></cite>。ル</div></blockquote>);
1249      my $txt = &text_to_html(<<"EOD", toc=>1);    } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
1250  *HEADER1      return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);
1251  **HEADER1-1    } else {
1252  -ITEM1      return $embedded;
1253  -ITEM2    }
1254  -ITEM3  }
1255  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  
1256  PAR1PAR1PAR1PAR1PAR1PAR1''BOLD''PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  sub load_formatter (@) {
1257  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1      for my $t (@_) {
1258            unless ($fmt{$t}) {
1259  PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2              require Message::Util::Formatter;
1260  PAR2PAR2PAR2PAR2PAR2PAR2'''ITALIC'''PAR2PAR2PAR2PAR2PAR2PAR2PAR2              $fmt{$t} = Message::Util::Formatter->new;
1261  PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2              for (@{$SuikaWiki::Plugin::List{'wiki'.$t}||[]}) {
1262  **HEADER1-2                  $_->load_formatter ($fmt{$t}, type => 'wiki'.$t);
1263  :TERM1:DESCRIPTION1 AND ''BOLD''              }
1264  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1          }
1265  PAR1PAR1PAR1PAR1PAR1PAR1''BOLD''PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1      }
1266  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1  }
1267  :TERM2:DESCRIPTION2  
1268  :TERM3:DESCRIPTION3  sub do_wikiform {
1269  ----      my $content = $database{$form{mypage}};
1270  *HEADER2      my $anchor = &get_new_anchor_index ($content);
1271  **HEADER2-1      &load_formatter (qw/form_template form_option/);
1272  http://www.hyuki.com/      my $write = 0;
1273  **HEADER2-2      my $i = 1;
1274        $content =~ s{$embed_command{form}}{
1275  [[YukiWiki2]]          my ($embed, $wfname, $template, $option) = ($&, $1, $3, $4);
1276            if (($wfname && $wfname eq $form{wikiform_targetform})
1277  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1              || $i == $form{wikiform_index}) {
1278  PAR1PAR1PAR1PAR1PAR1PAR1'''''BOLD ITALIC'''''PAR1PAR1PAR1PAR1PAR1              $template =~ s/\\(.)/$1/g;
1279  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1              $option =~ s/\\(.)/$1/g;
1280  >PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2              my $param = bless {}, 'SuikaWiki::Plugin';
1281  >PAR2PAR2PAR2PAR2PAR2PAR2'''ITALIC'''PAR2PAR2PAR2PAR2PAR2PAR2PAR2              $param->{page} = $form{mypage};
1282  >PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2              $param->{form_index} = $i;
1283                $param->{form_name} = $wfname;
1284  LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0              $param->{anchor_index} = $anchor;
1285                $param->{argv} = \%form;
1286  >LEVEL1              $param->{default_name} = $1 if $content =~ /default-name="([^"]+)"/;
1287  >LEVEL1              $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
1288  >LEVEL1              $fmt{form_option}->replace ($option, $param);
1289  >>LEVEL2              my $t = 1;
1290  >>LEVEL2              for (@{$param->{require}||[]}) {
1291  >>LEVEL2                  (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
1292  >>>LEVEL3              }
1293  -HELLO-1              $t = $fmt{form_template}->replace ($template, $param) if $t;
1294  --HELLO-2              if (length $t) {
1295  (HELLO-2, HELLO-2, HELLO-2)                  if ($param->{output}->{reverse}) {
1296  ---HELLO-3                      $embed .= "\n" . $t;
1297  (HELLO-3, HELLO-3, HELLO-3)                  } else {
1298  --HELLO-2                      $embed = $t . "\n" . $embed;
1299  ---HELLO-3                  }
1300  --HELLO-2                  $write = 1;
1301  ---HELLO-3                  $form{__comment_anchor_index} = $anchor
1302  >>>LEVEL3                    if $param->{anchor_index_};  ## $anchor is used!
1303  >>>LEVEL3              }
1304  >>>LEVEL3              $form{__wikiform_anchor_index} = $i;
1305  >>>LEVEL3              undef $form{wikiform_targetform};  ## make sure never to match
1306  EOD              undef $form{wikiform_index};       ## with WikiForm in rest of page
1307      print $txt;          }
1308      exit;          $i++; $embed;
1309  }      }ge;
1310        unless ($write) {
1311  sub do_diff {        #$content = "#?SuikaWiki/0.9\n\n" unless $content;
1312      if (not &is_editable($form{mypage})) {        #$content .= "\n" unless $content =~ /\n$/s;
1313          &do_read;        #
1314          return;      }
1315      }      if ($write) {
1316      &open_diff;          $form{mymsg} = $content;
1317      my $title = $form{mypage};          $form{mytouch} = 'on';
1318      &print_header($title);          &do_write;
1319      $_ = &escape($diffbase{$form{mypage}});      } else {
1320      &close_diff;          $form{mycmd} = 'read';
1321      print qq(<h3>$resource{difftitle}</h3>);          &do_read;
1322      print qq($resource{diffnotice});      }
1323      print qq(<pre class="diff">);  }
1324      foreach (split(/\n/, $_)) {  
1325          if (/^\+(.*)/) {  sub code_convert {
1326              print qq(<b class="added">$1</b>\n);    require Jcode;
1327          } elsif (/^\-(.*)/) {      my ($contentref, $code) = (shift, shift || $kanjicode);
1328              print qq(<s class="deleted">$1</s>\n);      $code = 'jis' if $code =~ /iso/;
1329          } elsif (/^\=(.*)/) {      $code = 'euc' if $code =~ /euc/;
1330              print qq(<span class="same">$1</span>\n);      $code = 'sjis' if $code =~ /shift/;
1331          } else {      $code = 'utf8' if $code =~ /utf/;
1332              print qq|??? $_\n|;      #&Jcode::convert($contentref, $code);       # for Jcode.pm
1333          }  #    &jcode::convert($contentref, $code);       # for jcode.pl
1334      }      #&Jcode::tr ($contentref, "\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA\xA1\xF5\xA1\xA4\xA1\xA5\xA1\xA7\xA1\xA8\xA1\xA9\xA1\xAA\xA1\xAE\xA1\xB0\xA1\xB2\xA1\xBF\xA1\xC3\xA1\xCA\xA1\xCB\xA1\xCE\xA1\xCF\xA1\xD0\xA1\xD1\xA1\xDC\xA1\xF0\xA1\xF3\xA1\xF4\xA1\xF6\xA1\xF7\xA1\xE1\xA2\xAF\xA2\xB0\xA2\xB2\xA2\xB1\xA1\xE4\xA1\xE3\xA1\xC0\xA1\xA1" => q(0-9A-Za-z&,.:;?!`^_/|()[]{}+$%#*@='"~-><\ )) if $code eq 'euc';
1335      print qq(</pre>);      $$contentref = Jcode->new ($contentref)->tr ("\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA\xA1\xF5\xA1\xA4\xA1\xA5\xA1\xA7\xA1\xA8\xA1\xA9\xA1\xAA\xA1\xAE\xA1\xB0\xA1\xB2\xA1\xBF\xA1\xC3\xA1\xCA\xA1\xCB\xA1\xCE\xA1\xCF\xA1\xD0\xA1\xD1\xA1\xDC\xA1\xF0\xA1\xF3\xA1\xF4\xA1\xF6\xA1\xF7\xA1\xE1\xA2\xAF\xA2\xB0\xA2\xB2\xA2\xB1\xA1\xE4\xA1\xE3\xA1\xC0\xA1\xA1" => q(0-9A-Za-z&,.:;?!`^_/|()[]{}+$%#*@='"~-><\ ))->$code;
1336      print qq(<hr>);      return $$contentref;
1337      &print_footer($title);  }
1338  }  
1339    sub do_diff {
1340  sub do_rss {      if (not &is_editable($form{mypage})) {
1341      my $rss = new Yuki::RSS(          &do_read;
1342          version => '1.0',          return;
1343          encoding => $charset,      }
1344      );      &open_diff;
1345      $rss->channel(      my $title = $form{mypage};
1346          title => $modifier_rss_title,      &print_header($title, -noindex => 1);
1347          link  => $modifier_rss_link,      $_ = &escape($diffbase{$form{mypage}});
1348          description => $modifier_rss_description,      &close_diff;
1349      );      print qq(<h3>@{[&Resource('Diff:Title',escape=>1)]}</h3>);
1350      my $recentchanges = $database{$RecentChanges};      print qq(<p>@{[&Resource('Diff:Notice',escape=>1)]}</p>);
1351      my $count = 0;      print qq(<pre class="diff">);
1352      foreach (split(/\n/, $recentchanges)) {      foreach (split(/\n/, $_)) {
1353          last if ($count >= 15);          if (/^\+(.*)/) {
1354          /^\- \d\d\d\d\-\d\d\-\d\d \(...\) \d\d:\d\d:\d\d (\S+)/;    # date format.              print qq(<ins class="added">$1</ins>\n);
1355          my $title = &unarmor_name($1);          } elsif (/^\-(.*)/) {
1356          my $escaped_title = &escape($title);              print qq(<del class="deleted">$1</del>\n);
1357          my $link = $modifier_rss_link . '?' . &encode($title);          } elsif (/^\=(.*)/) {
1358          my $description = $escaped_title . &escape(&get_subjectline($title));              print qq(<span class="same">$1</span>\n);
1359          $rss->add_item(          } else {
1360              title => $escaped_title,              print qq|??? $_\n|;
1361              link  => $link,          }
1362              description => $description,      }
1363          );      print qq(</pre>);
1364          $count++;      &print_footer($title);
1365      }  }
1366      # print RSS information (as XML).  
1367      print <<"EOD"  sub do_rss {
1368  Content-type: text/xml      eval q{use Yuki::RSS};
1369        my $rss = new Yuki::RSS(
1370  @{[$rss->as_string]}          version => '1.0',
1371  EOD          encoding => &get_charset_name ($kanjicode),
1372  }      );
1373        my $scheme = 'http';
1374  sub is_exist_page {      $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
1375      my ($name) = @_;      my $myuri = "$scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi";
1376      if ($use_exists) {      $rss->stylesheet (
1377          return exists($database{$name});        href      => $myuri . "?mycmd=TEXT_CSS;mypage=WikiStyle:RSS",
1378      } else {        type      => 'text/css',
1379          return $database{$name};      );
1380      }      $rss->channel(
1381  }          title   => &Resource ('RSS:WikiTitle'),
1382            link    => $myuri,
1383  1;          description     => &Resource ('RSS:WikiDescription'),
1384  __END__          'dc:language'   => $lang,
1385  =head1 NAME      );
1386        my $recentchanges = $database{RecentChanges};
1387  wiki.cgi - This is YukiWiki, yet another Wiki clone.      my $count = 0;
1388        foreach (split(/\n/, $recentchanges)) {
1389  =head1 DESCRIPTION          last if ($count >= 15);
1390            if (/\[\[([^]]+)\]\]/) {
1391  YukiWiki is yet another Wiki clone.            my $title = $1;
1392              $rss->add_item (
1393  YukiWiki can treat Japanese WikiNames (enclosed with [[ and ]]).              title       => &escape($title),
1394  YukiWiki provides 'InterWiki' feature, RDF Site Summary (RSS),              link        => $myuri . '?' . &encode($title),
1395  and some embedded commands (such as [[#comment]] to add comments).              description => &escape(&get_subjectline($title,delimiter=>'')),
1396                'dc:date'   => &get_info ($title, $info_LastModified),
1397  Read F<readme_en.txt> (English) or F<readme_ja.txt> (Japanese) in more detail.            );
1398              $count++;
1399  =head1 AUTHOR          }
1400        }
1401  Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/      # print RSS information (as XML).
1402        print <<"EOD"
1403  =head1 LICENSE  Content-type: application/xml; charset=@{[&get_charset_name ($kanjicode)]}
1404    
1405  Copyright (C) 2000-2002 by Hiroshi Yuki.  @{[$rss->as_string]}
1406    EOD
1407  This program is free software; you can redistribute it and/or  }
1408  modify it under the same terms as Perl itself.  
1409    sub _rfc3339_date ($) {
1410  =cut    my @time = gmtime (shift);
1411      sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
1412    }
1413    
1414    sub is_exist_page {
1415        my ($name) = @_;
1416        if ($use_exists) {
1417            return exists($database{$name});
1418        } else {
1419            return $database{$name};
1420        }
1421    }
1422    
1423    sub __get_database ($) { $database{ $_[0] } }
1424    sub __set_database ($$) { $database{ $_[0] } = $_[1] }
1425    
1426    sub do_map {
1427        my $page = $form{mypage};
1428        &print_header ($page);
1429        wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
1430        wiki::useragent::add ($ENV{HTTP_USER_AGENT});
1431        my ($r, $c) = get_search_result ($form{mypage});
1432        my $rl = wiki::referer::list_html ($form{mypage});
1433        print "<h2>@{[&Resource('Map:Title',escape=>1)]}</h2>\n<p>@{[&Resource('Map:Description',escape=>1)]}</p>\n";
1434        my %option = (level => 0+&Resource('Map:Depth'), weight_list => {}, not_exist => {},
1435          map_from_here => &Resource('Map:FromHere'),
1436          map_from_here_description => &Resource('Map:FromHereLong'));
1437        &wiki::map::make_list ($page, %option);
1438        print &wiki::map::list_to_html ($page, $option{weight_list}, %option);
1439        if ($c) {
1440          print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};
1441          print $r;
1442        }
1443        if ($rl) {
1444          print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
1445        }
1446        &print_footer ($page);
1447    }
1448    
1449    my %_Resource;
1450    sub Resource ($;%) {
1451      my ($s, %o) = @_;
1452      unless (defined $_Resource{$s}) {
1453        $_Resource{$_[0]} = &wiki::resource::get ($s, $_Resource{__option});
1454      }
1455      $o{escape} ? &escape ($_Resource{$s}) : $_Resource{$s};
1456    }
1457    
1458    package wiki::referer;
1459    sub add ($$) {
1460      my $page = shift;
1461      my $uri = shift;
1462      unless (ref $uri) {
1463        require URI;
1464        $uri = URI->new ($uri);
1465        ## Some schemes do not have query part.
1466        eval q{ $uri->query (undef) if $uri->query =~ /^[0-9]{6,8}$/ };
1467        $uri->fragment (undef);
1468      }
1469      $uri = $uri->canonical;
1470      return unless $uri;
1471      for my $regex (&get_dont_record) {
1472        return if $uri =~ /$regex/;
1473      }
1474      my %list = get ($page);
1475      $list{ $uri }++;
1476      set ($page, \%list);
1477    }
1478    sub get ($) {
1479      my $page = shift;
1480      split /"/, main::get_info ($page, 'Referer');
1481    }
1482    sub set ($%) {
1483      my $page = shift;
1484      my $list = shift;
1485      main::set_info ($page, Referer => join '"', %$list);
1486    }
1487    
1488    sub get_dont_record () {
1489      map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1490      grep !/^#/,
1491      split /[\x0D\x0A]+/, &main::__get_database ('RefererDontRecord');
1492    }
1493    sub get_site_name () {
1494      my @lines = grep /[^#]/, split /[\x0D\x0A]+/, &main::__get_database('RefererSiteName');
1495      my @item;
1496      for (@lines) {
1497        next if /^#/;
1498        my ($uri, $name) = split /\s+/, $_, 2;
1499        $uri =~ s/\$/\\\$/g;  $uri =~ s/\@/\\\@/g;  $uri =~ s/\//\\\//g;
1500        $name =~ s!([()/\\])!\\$1!g;  $name =~ s/\$([0-9]+)/).__decode (\${$1}).q(/g;
1501        push @item, [$uri, qq(q($name))];
1502      }
1503      @item;
1504    }
1505    
1506    sub list_html ($) {
1507      my $page = shift;
1508      my %list = get ($page);
1509      my $r = '';
1510      my @name = get_site_name;
1511      for my $uri (sort keys %list) {
1512        my $title;
1513        for my $item (@name) {
1514          if ($uri =~ /$item->[0]/) {
1515            $title = $uri;
1516            eval qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e}
1517              or die $@ ;#. qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e};
1518            last;
1519          }
1520        }
1521        my $euri = main::escape ($uri);
1522        if ($title) {
1523          $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri&gt;">@{[main::escape ($title)]}</a></li>\n);
1524        } else {
1525          $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1526        }
1527      }
1528      $r ? qq(<ul>$r</ul>\n) : '';
1529    }
1530    
1531    sub __decode ($) {
1532      my $s = shift;
1533      $s =~ tr/+/ /;
1534      $s =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/chr hex $1/ge;
1535      main::code_convert (\$s);
1536    }
1537    
1538    package wiki::useragent;
1539    
1540    sub add ($) {
1541      my $s = shift;
1542      return unless length $s;
1543      $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1544      my %ua;
1545      for (split /\n/, &main::__get_database('WikiUserAgentList')) {
1546        if (/^-\[(\d+)\] (.+)$/) {
1547          my ($t, $n) = ($1, $2);
1548          $n =~ tr/\x0A\x0D//d;
1549          $ua{$n} = $t;
1550        }
1551      }
1552      $ua{$s}++;
1553      my $s = qq(#?SuikaWiki/0.9\n);
1554      for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1555        $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1556      }
1557      &main::__set_database ('WikiUserAgentList' => $s);
1558    }
1559    
1560    package wiki::suikawikiconst;
1561    
1562    sub to_hash ($;$) {
1563      my $page = shift;
1564      my $h = shift || {};
1565      my $val;
1566      for my $line (split /\n/, $page) {
1567        $line =~ tr/\x0A\x0D//d;
1568        if ($val && $line =~ s/^\s+//) {
1569          $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
1570        } elsif ($line =~ /^(.+):/) {
1571          $val = $1; $h->{$val} = '';
1572        }
1573      }
1574      $h;
1575    }
1576    
1577    package SuikaWiki::Plugin;
1578      our $plugin_directory;  # defined in top of this file.
1579      our %List;
1580    
1581    sub escape ($$) { main::escape ($_[1]) }
1582    sub unescape ($$) { main::unescape ($_[1]) }
1583    sub encode ($$) { main::encode ($_[1]) }
1584    sub decode ($$) { main::decode ($_[1]) }
1585    sub __get_datetime ($) { main::get_now () }
1586    sub resource ($$;%) { shift; &main::Resource (@_) }
1587    sub uri ($$) { $main::uri{$_[1]} }
1588    
1589    sub regist ($@) {
1590        my $pack = shift;
1591        for (@_) {
1592            push @{$List{$_}}, $pack;
1593        }
1594    }
1595    
1596    sub import_plugins () {
1597        opendir PDIR, $plugin_directory;
1598        my @plugin = grep {s/\.pm$//} readdir (PDIR);
1599        closedir PDIR;
1600        for (@plugin) {
1601            eval qq{ use SuikaWiki::Plugin::$_ } unless /[^A-Za-z0-9_]/;
1602            push @{$List{_all}}, qq(SuikaWiki::Plugin::$_);
1603        }
1604    }
1605    
1606    &import_plugins ();
1607    
1608    package wiki::conneg;
1609    
1610    ## BUG: this parser isn't strict.
1611    sub get_accept_lang (;$) {
1612      my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1613      my %alang = (ja => 0.0002, en => 0.0001);
1614      my $i = 0.1;
1615      for (split /\s*,\s*/, $alang) {
1616        tr/\x09\x0A\x0D\x20//d;
1617        if (/((?:(?!;q=).)+)(?:;q="?([0-9.]+)"?)?/) {
1618          my $l = lc $1; $l =~ tr/\x22\x5C//d;
1619          $alang{$l} = (defined $2 ? $2 : 1.000)*1000;
1620          $alang{$l} += $i unless $alang{$l} == 0;
1621          $i -= 0.001;
1622        }
1623      }
1624      \%alang;
1625    }
1626    
1627    package wiki::resource;
1628    
1629    sub get ($;\%) {
1630      my ($resname, $option) = @_;
1631      $option->{accept_language} ||= &wiki::conneg::get_accept_lang ();
1632      $option->{resource} ||= {};
1633      my $v;
1634      for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1635        while (length $lang) {
1636          unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1637            $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash (&main::__get_database('WikiResource:'.$lang));
1638            $v = $option->{resource}->{$lang}->{$resname};
1639            last if defined $v;
1640          }
1641          $lang =~ s/[^+-]*$//; $lang =~ s/[+-]$//;
1642        }
1643        last if defined $v;
1644      }
1645      defined $v ? $v : $resname;
1646    }
1647    
1648    package wiki::map;
1649    
1650    sub make_list ($;%) {
1651      my ($page, %option) = @_;
1652      $option{level} ||= 3;
1653      my %weight;
1654      my $content = &main::__get_database ($page);
1655      $content =~ s{^\#\?([^\x0A\x0D]+)}{
1656        if ($1 =~ /import="([^"]+)"/) {
1657          for (split /\s*,\s*/, $1) {
1658            $weight{$_} += 2;
1659          }
1660        }
1661        $&;
1662      }ges;
1663      ## Bug: this code does not support content type.
1664      $content =~ s{\[\[((?!\#)[^]]+)\](?:>>\d+)?\]}{
1665        $weight{$1}++; $&;
1666      }ge;
1667      delete $weight{$page};        ## Delete myself
1668      for my $page (keys %weight) {
1669        my $w = ($content =~ s/\Q$page\E/$&/g);
1670        $weight{$page} += $w + $weight{$page}; ## Weight of [[name]] is x2.
1671        ($weight{$page} *= 0.1, $option{not_exist}->{$page} = 1) unless &main::is_exist_page ($page);
1672      }
1673      $option{weight_list}->{$page} = \%weight;
1674      if (--$option{level}) {
1675        for my $page (keys %weight) {
1676          &make_list ($page, %option) unless $option{weight_list}->{$page};
1677        }
1678      }
1679      $option{weight_list};
1680    }
1681    
1682    sub list_to_html ($$;%) {
1683      my ($Page, $wlist, %option) = @_;
1684      my $r = '';
1685      $option{outputed}->{$Page} = 1;
1686      for my $page (sort {$wlist->{$Page}->{$b} <=> $wlist->{$Page}->{$a}} keys %{$wlist->{$Page}}) {
1687        $r .= qq(<li><span class="weight">[@{[0+$wlist->{$Page}->{$page}]}]</span> <a href="$main::url_cgi?@{[&main::encode($page)]}" class="wiki@{[$option{not_exist}->{$page}?' not-exist':'']}">@{[&main::escape ($page).($option{not_exist}->{$page}?qq(<span class="mark">@{[&main::Resource('JumpAndEditWikiPageMark',escape=>1)]}</span>):'')]}</a> <a href="$main::url_cgi?mycmd=map;mypage=@{[&main::encode($page)]}" class="wiki-cmd map-from-here" title="@{[&main::escape($option{map_from_here_description})]}">@{[&main::escape($option{map_from_here})]}</a> <span class="summary">@{[&main::escape(&main::get_subjectline($page))]}</span>);
1688        unless ($option{outputed}->{$page}) {
1689          $r .= &list_to_html ($page, $wlist, %option);
1690        }
1691        $r .= "</li>\n";
1692      }
1693      $r ? qq(<ul class="map">$r</ul>) : '';
1694    }
1695    
1696    package main;
1697    &main;
1698    exit 0;
1699    
1700    1;
1701    __END__
1702    =head1 NAME
1703    
1704    wiki.cgi - This is YukiWiki, yet another Wiki clone.
1705    walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.
1706    
1707    =head1 DESCRIPTION
1708    
1709    YukiWiki is yet another Wiki clone.
1710    
1711    YukiWiki can treat Japanese WikiNames (enclosed with [[ and ]]).
1712    YukiWiki provides 'InterWiki' feature, RDF Site Summary (RSS),
1713    and some embedded commands (such as [[#comment]] to add comments).
1714    
1715    Read F<readme_en.txt> (English) or F<readme_ja.txt> (Japanese) in more detail.
1716    
1717    =head1 AUTHOR
1718    
1719    Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/
1720    
1721    =head1 LICENSE
1722    
1723    Copyright (C) 2000-2002 by Hiroshi Yuki.
1724    
1725    This program is free software; you can redistribute it and/or
1726    modify it under the same terms as Perl itself.
1727    
1728    =cut

Legend:
Removed from v.1.1.1.1  
changed lines
  Added in v.1.44

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24