/[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.7 by wakaba, Mon Feb 4 15:27:22 2002 UTC revision 1.42 by wakaba, Mon Dec 30 03:20:06 2002 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl  #!/usr/bin/perl
2  use lib "../lib";  # wiki.cgi - This is YukiWiki, yet another Wiki clone.
 use CGI::Carp 'fatalsToBrowser';  
 use Algorithm::Diff qw(traverse_sequences);  
 # use strict;  
3  #  #
4  # yukiwiki.cgi - Yet another WikiWikiWeb 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,2001 by Hiroshi Yuki.  
7  # <hyuki@hyuki.com>  use strict;
8  # http://www.hyuki.com/yukiwiki/  use lib qw(./WalWiki/lib);
9  #  use CGI::Carp qw(fatalsToBrowser);
10  # This program is free software; you can redistribute it and/or modify  use Yuki::DiffText qw(difftext);
11  # it under the terms of the GNU General Public License as published by  use Fcntl;
 # the Free Software Foundation; either version 2 of the License, or  
 # (at your option) any later version.  
12  #  #
13  # This program is distributed in the hope that it will be useful,  # You MUST modify following '$modifier_...' variables.
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
 # GNU General Public License for more details.  
14  #  #
15  # $Id$  # my $modifier_dbtype = 'AnyDBM_File';  # Fast, not available on some server, page size limited.
16  ##############################  # my $modifier_dbtype = 'dbmopen';      # Fast, not available on some server, page size limited.
17  my $version = "1.6.6";  my $modifier_dbtype = 'YukiWikiDB';     # Slow, available on all environment.
18  ##############################  my $modifier_dir_data = './wikidata'; # Your data directory.
19  # 単独テストのときには 1 にする。  our $url_cgi = '/~wakaba/-temp/wiki/wiki';
20  my $testing = 0;          ## - MUST be started by '/'
21  ##############################          ## - MUST NOT include [&<>"] and/or non-URI characters
22  # 漢字ライブラリ  our %uri;
23  my $jcodelib = 'jcode.pl';  $uri{wiki} = $url_cgi;
24  ##############################  $uri{cvs_wikipage} = '/gate/cvs/wakaba/suikawiki/wiki/';
25  # 保存・表示の漢字コード  $SuikaWiki::Plugin::plugin_directory = q(./SuikaWiki/Plugin/);
26  my $kanjicode = 'euc';     # 'sjis' 'euc'  my $file_touch = "$modifier_dir_data/touched.txt";
 my $charset = 'euc-jisx0213';  # 'Shift_JIS' 'EUC-JP'  
 ##############################  
 # dbmopenが使えるなら1、使えないなら0  
 my $dbmopen = 0;  
 ##############################  
 # データベース名(.pag, .dir, .dbなどは不要)  
 # $dbmopen = 1のときはデータベース名、  
 # $dbmopen = 0のときはディレクトリ名になる。  
 my $dbname = './wikidata';  
 my $diffdbname = './wikidiff';  
 ##############################  
 # 修正者の氏名(自由に変更してください)  
 my $modifier = 'suika';  
 ##############################  
 # 修正者のWebページ(自由に変更してください)  
 my $modifierlink = 'http://suika.fam.cx/';  
 ##############################  
 # このページのURL  
 my $thisurl = 'wiki';  
 ##############################  
 # 開始ページ名  
 my $toppage = 'HomePage';  
 ##############################  
 # 最終更新ページ名  
 my $whatsnew = 'RecentChanges';  
 ##############################  
 # 最終更新に掲載するページ数  
 my $maxnew = 50;  
27  ##############################  ##############################
 # アイコンファイル名(カラー版)  
 my $iconfile = '';  
 ##############################  
 # アイコンファイル名(モノクロ版)  
 # my $iconfile = '';  
 ##############################  
 # ページを変更したときにtouchするファイル(''なら何もしない)  
 my $touchfile = 'touch.txt';  
 ##############################  
 # プレビュー用の背景色  
 my $preview_color = '#FFCCCC';  
 ##############################  
 # 全ページのスタイル  
 my $style = <<'EOD';  
 pre, dl, ul, ol, p, blockquote { line-height:120%; }  
 a { text-decoration: none; }  
 a:link { color: #0000FF; background-color: #FFFFFF; }  
 a:visited { color: #9900CC; background-color: #FFFFFF; }  
 a:hover { text-decoration: underline; }  
 EOD  
 ##############################  
 # テキスト入力部分の大きさ  
 my $cols = 80;  
 my $rows = 20;  
 ##############################  
 my %form = ();  
 my %database = ();  
 my %diffbase = ();  
 my $diff_text = '';  
 my @diff_added = ();  
 my @diff_deleted = ();  
 my $msgrefA;  
 my $msgrefB;  
 ##############################  
 # 編集不可ページ名一覧  
 my @uneditable = ( $whatsnew );  
 ##############################  
 # リンク用の正規表現  
 # YukiWikiのリンクは2種類ある。  
 #  
 # (1) WikiName (RecentChangesとかFrontPageのようなもの)  
 # (2) BracketName ([[結城浩]]とか[[トラブルシュート]]のようなもの)  
28  #  #
29  # ※シフトJISの2バイト目には ']' が来うるので、  # You MAY, but do NOT NEED modify following variables.
30  # 文字']'を1つ多くとるようにしている。  #
31  #  my $dataname = "$modifier_dir_data/wiki";
32  my $WikiName = '([A-Z][a-z]+([A-Z][a-z]+)+)';  my $infoname = "$modifier_dir_data/info";
33  my $BracketName = '\[\[([^>\s]+?\]?)\]\]';  my $diffname = "$modifier_dir_data/diff";
34    my $use_exists = 0; # If you can use 'exists' method for your DB.
35  # アイコン部分のタグ  ##############################
36  my $IconTag = ''; #<<"EOD";  my $FrontPage = 'HomePage';
37  #<a href="http://www.hyuki.com/yukiwiki/"><img src="$iconfile"  my $IndexPage = 'IndexPage';
38  # border="0" width="80" height="80" alt="[YukiWiki]" /></a>  my $SearchPage = 'SearchPage';
39  #EOD  my $CreatePage = 'CreatePage';
40    my $ErrorPage = 'ErrorPage';
41  require "$jcodelib";  my $RssPage = 'RssPage';
42    my $AdminSpecialPage = 'Admin Special Page'; # must include spaces.
43  &init_form($kanjicode);  my %PageName = (
44      DefaultStyleForHTML   => 'WikiHTMLStyle',
45  if ($testing) {  );
46      %form = (  ##############################
47          # 'mycmd' => 'write',  my %fmt;        ## formatter objects
48          'mycmd' => 'read',  my %embed_command = (
49          #'mycmd' => 'search',          searched        => '^\[\[#searched:([^\]]+)\]\]$',
50          #'mycmd' => 'edit',          form    => qw/\[\[\#form(?:\(([A-Za-z0-9-]+)\))?:'((?:[^'\\]|\\.)*)':'((?:[^'\\]|\\.)*)'(?::'((?:[^'\\]|\\.)*)')?\]\]/,
51          'mymsg' => <<"EOD",  );
52  はじめまして。  ##############################
53  これからいろいろ書き込みますね。  my $info_LastModified = 'LastModified';
54  LinkPageも見てください。  my $info_IsFrozen = 'IsFrozen';
55  TestPageはどうでしょうか。  ##############################
56  どうぞよろしく。  my $kanjicode = 'euc';
57  http://www.hyuki.com/  my $lang = 'ja';
58  [[結城浩]]  my %fixedpage = (
59  EOD      $IndexPage => 1,
60          'mypage' => '<結城浩>',      $ErrorPage => 1,
61          'myword' => '結',      $RssPage => 1,
62          # '3C8C8B8FE98D5F3E' => '',      RecentChanges => 1,
63          # 'TestPage' => '',      AdminChangePassword => 1,
64      );      CompletedSuccessfully => 1,
65  }      WikiUserAgentList => 1,
66  &main;  );
67  exit(0);  my %form;
68    my %database;
69    my %infobase;
70    my %diffbase;
71    my %interwiki;
72    ##############################
73    my %page_command = (
74        $IndexPage => 'index',
75        $RssPage => 'rss',
76        AdminChangePassword => 'adminchangepasswordform',
77    );
78    my %command_do = (
79        read => \&do_read,
80        TEXT_CSS => \&do_output_css,
81        edit => \&do_edit,
82        adminedit => \&do_adminedit,
83        adminchangepasswordform => \&do_adminchangepasswordform,
84        adminchangepassword => \&do_adminchangepassword,
85        write => \&do_write,
86        index => \&do_index,
87        searchform => \&do_searchform,
88        comment => \&do_comment,
89        RandomJump  => \&do_random_jump,
90        rss => \&do_rss,
91        diff => \&do_diff,
92        wikiform    => \&do_wikiform,
93        map => \&do_map,
94    );
95    my $UA = '';  ## User agent name
96    $| = 1;
97    ##############################
98    
 # メイン  
99  sub main {  sub main {
100      &normalize_form;      $UA = $main::ENV{HTTP_USER_AGENT};
101      if ($dbmopen) {      &open_db;
102          if (!dbmopen(%database, $dbname, 0666)) {      &init_form;
103              &print_error("(dbmopen) $dbname が作れません。");      if ($command_do{$form{mycmd}}) {
104          }          &{$command_do{$form{mycmd}}};
105      } else {      } else {
106          if (!tie(%database, "YukiWikiDB", $dbname)) {          &{$command_do{read}};
             &print_error("(tie error)");  
         }  
     }  
   
     # myspecial対応  
     foreach (keys %form) {  
         if (/^myspecial_(.*)/) {  
             $form{mycmd} = $1;  
             last;  
         }  
107      }      }
108        &close_db;
109    }
110    
111      if ($form{mycmd} eq 'read') {  sub do_read {
112          &do_read;    my $content = $database{$form{mypage}};
113      } elsif ($form{mycmd} eq 'preview') {    #print "content-type:text/plain;charset=euc-jp\n\n".gmtime."Get Lastmodified\n";
114          &do_preview;    my $lm = &get_info($form{mypage}, $info_LastModified);
115      } elsif ($form{mycmd} eq 'write') {    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
116          &do_write;    wiki::useragent::add ($ENV{HTTP_USER_AGENT});
117      } elsif ($form{mycmd} eq 'edit') {    #print gmtime."Search...\n";
118          &do_edit;    my ($r, $c) = get_search_result ($form{mypage});
119      } elsif ($form{mycmd} eq 'reedit') {    my $rl = wiki::referer::list_html ($form{mypage});
120          &do_reedit;    my @toc;
121      } elsif ($form{mycmd} eq 'search') {    push @toc, qq(-<a href="#wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</a>) if $c;
122          &do_search;    push @toc, qq(-<a href="#wikipage-referer">@{[&Resource('Referers',escape=>1)]}</a>) if $rl;
123      } elsif ($form{mycmd} eq 'list') {      my $cf = 'SuikaWiki/0.9';
124          &do_list;      ## Should be support at least:
125      } elsif ($form{mycmd} eq 'diff') {      ## - 'SuikaWiki/0.9' CRLF
126          &do_diff;      ## - 'H2H/' ("0.9" / "1.0" / "1.1") CRLF
127      } else {      ## - "/*" WSP* 'W3C-CSS/' ("1.0" / "2.0") "*/" CRLF
128          $form{mypage} = $toppage;      $cf = $1 if $content =~ s#^(?:/\*\s*|[\#<]\?)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+##s;
129          &do_read;      if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
130      }      #print gmtime."Header...\n";
131      if ($dbmopen) {        &print_header ($form{mypage}, -last_modified => $lm, -expires => time + 120,
132          dbmclose(%database);          -content_format => $cf, -noindex => ($cf =~ /obsoleted="yes"/ ? 1 : 0));
133            #print "\n". gmtime."Body...\n";
134          &print_content ($content, content_format => $cf, last_modified => $lm,
135            -toc => \@toc);
136          print &text_to_html (q([[#comment]])) if $cf !~ /obsoleted="yes"/ && !$fixedpage{$form{mypage}};
137      } else {      } else {
138          untie(%database);        &print_header($form{mypage}, -expires => time + 120, -last_modified => $lm);
139          print "<pre>@{[&escape($content)]}</pre>";
140      }      }
141        if ($c) {
142          print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};
143          print $r;
144        }
145        if ($rl) {
146          print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
147        }
148            #print "\n". gmtime."Footer...\n";
149      &print_footer($form{mypage}, $lm);
150            #print "\n". gmtime."Fin...\n";
151    }
152    
153    sub do_output_css {
154      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
155      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
156      my $content = $database{$form{mypage}};
157      if ($content =~ m#^\s*/\*\s*W3C-CSS#) {
158        my $lm = gmtime &get_info($form{mypage}, $info_LastModified);
159        print "Content-Type: text/css; charset=@{[&get_charset_name($kanjicode)]}\n";
160        print "Last-Modified: $lm\n";
161        print "Expires: @{[scalar gmtime time+3600]}\n";    ## TODO: don't use asctime
162        print "\n";
163        print $content;
164      } else {
165        print "Status: 406 Unsupported Media Type\n";
166        &print_header('WikiPageIsNotCSS', -noindex => 1);
167        &print_content($database{WikiPageIsNotCSS});
168        &print_footer('WikiPageIsNotCSS');
169      }
170  }  }
171    
172  # ページの表示  sub id_and_name ($) {
173  sub do_read {      my $name = shift;
174      my $page_name = $form{mypage};      if ($UA =~ m#Mozilla/[12]\.|Microsoft Internet Explorer#) {
175      my $percent_name = &encode_percent($page_name);        qq{id="$name"><a name="$name"></a};
176      &print_header($page_name);      } else {
177      print qq|<h1>$IconTag<a href="$thisurl?mycmd=search;myword=$percent_name">$page_name</a></h1>\n|;          qq{id="$name"};
178      &print_toolbar($page_name);      }
     print &convert_html(&get_page($page_name));  
     &print_footer;  
179  }  }
180    
 # ページの編集  
181  sub do_edit {  sub do_edit {
182      if (not &is_editable($form{mypage})) {      my ($page) = &unarmor_name(&armor_name($form{mypage}));
183          # 編集不可ページは表示のみ      if (not &is_editable($page)) {
184          &do_read;          &print_header($page, -noindex => 1);
185          return;          &print_message(&Resource('Error:ThisPageIsUneditable'));
186        } elsif (&is_frozen($page)) {
187            &print_header($page, -noindex => 1);
188            &print_message(&Resource('Error:ThisPageIsUneditable'));
189        } else {
190            &print_header($page, -noindex => 1, -expires => time+60);
191            &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);
192      }      }
193      &editpage(&get_page($form{mypage}));      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
194  }      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
195        my ($r, $c) = get_search_result ($form{mypage});
196  # ページの再編集      my $rl = wiki::referer::list_html ($form{mypage});
197  sub do_reedit {      if ($c) {
198      if (not &is_editable($form{mypage})) {        print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};
199          # 編集不可ページは表示のみ        print $r;
200          &do_read;      }
201        if ($rl) {
202          print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
203        }
204        &print_footer($page);
205    }
206    
207    sub do_adminedit {
208        my ($page) = &unarmor_name(&armor_name($form{mypage}));
209        &print_header($page, -noindex => 1);
210        if (not &is_editable($page)) {
211            &print_message(&Resource('Error:ThisPageIsUneditable'));
212      } else {      } else {
213          &editpage($form{mymsg});          &print_message(&Resource('Error:PasswordIsNotSpecified'));
214            &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);
215      }      }
216        &print_footer($page);
217  }  }
218    
219  sub editpage {  sub do_adminchangepasswordform {
220      my $page_msg = shift;      &print_header('AdminChangePassword', -noindex => 1);
221      my $page_name = $form{mypage};      &print_passwordform;
222      my $digest = &calc_message_digest($page_msg);      &print_footer('AdminChangePassword');
     &print_header($page_name);  
     print qq|<h1>$IconTag${page_name}の編集</h1>\n|;  
     &print_toolbar($page_name);  
     $page_msg = &escape($page_msg);  
     print <<"EOD";  
 <form action="$thisurl" method="post">  
 <!--<input type="hidden" name="mycmd" value="preview">-->  
 <input type="hidden" name="mypage" value="$page_name">  
 <input type="hidden" name="mydigest" value="$digest">  
 <textarea cols="$cols" rows="$rows" name="mymsg" wrap="virtual">$page_msg</textarea><br>  
 <input type="submit" name="myspecial_preview" value="確認">  
 <input type="submit" name="myspecial_write" value="確認せず変更">  
 </form>  
 <hr>  
 <h3>テキスト整形のルール</h3>  
   
 <p>通常は入力した文字がそのまま出力されますが、  
 以下のルールに従ってテキスト整形を行うことができます。</p>  
   
 <ul>  
 <li>  
 空行は段落の区切りとなります。  
   
 <li>  
 HTMLのタグは書けません。  
   
 <li>  
 ''強調''のようにシングルクォート二つではさむと、強調になります。  
   
 <li>  
 '''更に強調'''のようにシングルクォート三つではさむと、更に強調になります。  
   
 <li>  
 ----のようにマイナス4つがあると、水平線になります。  
   
 <li>  
 *を行頭に書くと大見出しになります。  
   
 <li>  
 **を行頭に書くと小見出しになります。  
   
 <li>  
 -を行頭に書くと箇条書きになります。- -- --- の3レベルがあります。  
   
 <li>  
 :を行頭に書くと用語と解説文が作れます。  
   
 <pre>  
     :用語1:いろいろ書いた解説文1  
     :用語2:いろいろ書いた解説文2  
     :用語3:いろいろ書いた解説文3  
 </pre>  
   
 <li>  
 http://www.hyuki.com/ のようなURLは自動的にリンクになります。  
   
 <li>  
 YukiWikiのように大文字小文字を混ぜた英文字列を書くと、  
 YukiWikiのページ名になります。  
   
 <li>  
 [[結城浩]]のように二重の大かっこ[[ ]]でくくった文字列を書くと、  
 YukiWikiのページ名になります。  
 大かっこの中にはスペースを含めてはいけません。  
 日本語も使えます。  
   
 <li>  
 行頭がスペースで始まっていると、  
 その段落は整形済み扱われます。  
 プログラムを書き込むときに使うと便利です。  
   
 <li>  
 &gt; を行頭に書くと、  
 引用文が書けます。  
 &gt; の数が多いとインデントが深くなります(3レベルまで)。  
   
 </ul>  
 EOD  
     &print_footer;  
223  }  }
224    
225  # ページの検索  sub do_adminchangepassword {
226  sub do_search {      if ($form{mynewpassword} ne $form{mynewpassword2}) {
227      if ($form{myword}) {          &print_error(&Resource('Error:PasswordMismatch'));
228          &print_header('検索結果');      }
229          print qq|<h1>$IconTag$form{myword}の検索結果</h1>\n|;      my ($validpassword_crypt) = &get_info($AdminSpecialPage, 'AdminPassword');
230          &print_toolbar();      if ($validpassword_crypt) {
231          print qq|<ul>\n|;          if (not &valid_password($form{myoldpassword})) {
232          my $count = 0;  #            &send_mail_to_admin(<<"EOD", "AdminChangePassword");
233          foreach my $page_name (sort keys %database) {    # sortするのは無謀かな  #myoldpassword=$form{myoldpassword}
234              if ($database{$page_name} =~ /\Q$form{'myword'}\E/) {  #mynewpassword=$form{mynewpassword}
235                  my $encoded = &encode_percent($page_name);  #mynewpassword2=$form{mynewpassword2}
236                  print qq|<li><a href="$thisurl?mycmd=read;mypage=$encoded">$page_name</a>\n|;  #EOD
237                  $count++;              &print_error(&Resource('Error:PasswordIsIncorrect'));
             }  
238          }          }
239          print qq|</ul>\n|;      }
240          if ($count > 0) {      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
241              print qq|<p><strong>$form{myword}</strong>を含むページは、上に示す<strong>$count</strong> ページです。</p>\n|;      my (@token) = ('0'..'9', 'A'..'Z', 'a'..'z');
242          } else {      my $salt1 = $token[(time | $$) % scalar(@token)];
243              print qq|<p><strong>$form{myword}</strong>を含むページは見つかりません。</p>\n|;      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
244        my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
245        &set_info($AdminSpecialPage, 'AdminPassword', $crypted);
246    
247        &print_header('CompletedSuccessfully', -noindex => 1);
248        &print_message(&Resource('Error:PasswordIsChanged'));
249        &print_footer('CompletedSuccessfully');
250    }
251    
252    sub do_index {
253      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
254      wiki::useragent::add ($ENV{HTTP_USER_AGENT});
255        &print_header($IndexPage);
256        print qq(<ul>);
257        foreach my $page (sort keys %database) {
258            if (&is_editable($page)) {
259                print qq(<li><a href="$url_cgi?@{[&encode($page)]}">@{[&escape($page)]}</a>@{[&escape(&get_subjectline($page))]}</li>);
260          }          }
     } else {  
         &print_header('単語検索');  
         print qq|<h1>$IconTag単語検索</h1>\n|;  
         &print_toolbar();  
261      }      }
262      print <<"EOD";      print qq(</ul>);
263  <p>      my ($r, $c) = get_search_result ($form{mypage});
264  <form action="$thisurl" method="post">      if ($c) {
265  <input type="hidden" name="mycmd" value="search">        print qq{<h2 @{[&id_and_name('wikipage-see-also')]}>@{[&Resource('SeeAlso',escape=>1)]}</h2>};
266  <input type="text" name="myword" size="20" value="$form{myword}">        print $r;
267  <input type="submit" value="単語検索">      }
268  </form>      my $rl = wiki::referer::list_html ($form{mypage});
269  </p>      if ($rl) {
270  EOD          print qq(<div @{[&id_and_name('wikipage-referer')]}><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
     &print_footer;  
 }  
   
 # ページの一覧  
 sub do_list {  
     &print_header('ページ一覧');  
     print qq|<h1>$IconTag ページ一覧</h1>\n|;  
     &print_toolbar();  
     print qq|<ul>\n|;  
     foreach my $page_name (sort keys %database) {    # sortするのは無謀かな  
         my $encoded = &encode_percent($page_name);  
         print qq|<li><a href="$thisurl?mycmd=read;mypage=$encoded">$page_name</a>\n|  
     }  
     print qq|</ul>\n|;  
     &print_footer;  
 }  
   
 # プレビュー  
 sub do_preview {  
     my $page_name = $form{mypage};  
     my $escapedmsg = &escape($form{mymsg});  
     &print_header($page_name);  
     print qq|<h1>$IconTag${page_name}のプレビュー</h1>\n|;  
     &print_toolbar($page_name);  
     # local $percent_name = &encode_percent($page_name);  
     print qq|<p>以下のプレビューを確認して、よければページ下部のボタンで更新してください。</p>\n|;  
     if ($form{mymsg}) {  
         print qq|<table width="100%" bgcolor="$preview_color" ><tr><td>\n|;  
         # print &convert_html($escapedmsg);  
         print &convert_html($form{mymsg});  
         print qq|</td></tr></table>\n|;  
     } else {  
         print qq|<p>(ページの内容は空です。更新するとこのページは<strong>削除</strong>されます。)</p>\n|;  
271      }      }
272      &print_preview_buttons($page_name, $escapedmsg, $form{mydigest});      &print_footer($IndexPage);
     &print_footer;  
273  }  }
274    
 sub print_preview_buttons {  
     my ($page_name, $escapedmsg, $digest) = @_;  
     print <<"EOD";  
     <form action="$thisurl" method="post">  
     <textarea cols="$cols" rows="$rows" name="mymsg" wrap="virtual">$escapedmsg</textarea>  
     <br />  
     <input type="hidden" name="mypage" value="$page_name">  
     <input type="hidden" name="mydigest" value="$digest">  
     <input type="submit" name="myspecial_preview" value="再度プレビュー">  
     <input type="submit" name="myspecial_write" value="ページの更新">  
     </form>  
 EOD  
 }  
   
 # 書き込む  
275  sub do_write {  sub do_write {
276      if (not &is_editable($form{mypage})) {      if (&frozen_reject()) {
         # 編集不可ページは表示のみ  
         &do_read;  
277          return;          return;
278      }      }
279    
280      my $page_name = $form{mypage};      if (not &is_editable($form{mypage})) {
281            &print_header($form{mypage}, -noindex => 1);
282            &print_message(&Resource('Error:ThisPageIsUneditable'));
283            &print_footer($form{mypage});
284            return;
285        }
286    
287      # digestを使って、更新の衝突チェック      if (&conflict($form{mypage}, $form{mymsg})) {
     my $original_digest = &calc_message_digest(&get_page($page_name));  
     if ($form{mydigest} ne $original_digest) {  
         &print_header($page_name);  
         print qq|<h1>$IconTag${page_name}で【更新の衝突】が起きました</h1>\n|;  
         print <<"EOD";  
 <p>あなたがこのページを編集している間に、  
 他の人が同じページを更新してしまったようです。  
 </p><p>  
 以下に、あなたの編集したテキストがありますので、  
 あなたの編集内容が失われないように、  
 いますぐ、メモ帳などにコピー&ペーストしてください。  
 </p><p>  
 コピー&ペーストが済んでから、  
 最新の内容を見て再度編集し直してください。  
 最新の内容は  
 <a target="_blank" href="$thisurl?mycmd=read;mypage=$form{mypage}">$form{mypage}</a>  
 で見ることができます。  
 </p>  
 EOD  
         # &print_toolbar($page_name);  
         &print_preview_buttons($page_name, &escape($form{mymsg}), $form{mydigest});  
         &print_footer;  
288          return;          return;
289      }      }
290    
291      # diff生成      # Making diff
292      {      {
293          &opendiff;          &open_diff;
294          my @msg1 = split(/\n/, &get_page($page_name));          my @msg1 = split(/\n/, $database{$form{mypage}});
295          my @msg2 = split(/\n/, $form{mymsg});          my @msg2 = split(/\n/, $form{mymsg});
296          $msgrefA = \@msg1;          $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);
297          $msgrefB = \@msg2;          &close_diff;
         &diff_check;  
         $diffbase{$form{mypage}} = $diff_text;  
         $diff_text = '';  
         &closediff;  
298      }      }
299    
     &print_header($page_name);  
     &set_page($page_name, $form{mymsg});  
300      if ($form{mymsg}) {      if ($form{mymsg}) {
301          print qq|<h1>$IconTag${page_name}を更新しました</h1>\n|;          $database{$form{mypage}} = $form{mymsg};
302          &print_toolbar($page_name);          #&send_mail_to_admin($form{mypage}, "Modify");
303          print &convert_html(&get_page($page_name));          if ($form{mytouch}) {
304      } else {              &set_info($form{mypage}, $info_LastModified, time);
305          print qq|<h1>$IconTag${page_name}を削除しました</h1>\n|;              &update_recent_changes;
         &print_toolbar($page_name);  
         print qq|<p>${page_name}を削除しました。</p>\n|;  
     }  
     &print_footer;  
     # 更新されたのでタッチしておく。  
     if ($touchfile) {  
         open(FILE, "> $touchfile");  
         print FILE "\n";  
         close(FILE);  
     }  
 }  
   
 # ページの変更点  
 sub do_diff {  
     if (not &is_editable($form{mypage})) {  
         # 編集不可ページは表示のみ  
         &do_read;  
         return;  
     }  
     &opendiff;  
     &print_header($form{mypage} . 'の変更点');  
     print qq|<h1>$IconTag <a href="$thisurl?mycmd=read&mypage=$form{mypage}">$form{mypage}</a>の変更点</h1>\n|;  
     &print_toolbar();  
     $_ = &escape($diffbase{$form{mypage}});  
     print <<"EOD";  
 <ul>  
 <li>追加された行は<ins>青色</ins>です。  
 <li>削除された行は<del>赤色</del>です。  
 <li><a href="$thisurl?mycmd=read;mypage=$form{mypage}">$form{mypage}</a>へ行く。  
 </ul>  
 <hr />  
 EOD  
     print qq|<pre>\n|;  
     foreach (split(/\n/, $_)) {  
         if (/^\+(.*)/) {  
             print qq|<ins>$1</ins>\n|;  
         } elsif (/^\-(.*)/) {  
             print qq|<del>$1</del>\n|;  
         } elsif (/^\=(.*)/) {  
             print qq|$1\n|;  
         } else {  
             print qq|??? $_\n|;  
         }  
     }  
     print qq|</pre>\n|;  
     &print_footer;  
     &closediff;  
 }  
   
 sub opendiff {  
     if ($dbmopen) {  
         if (!dbmopen(%diffbase, $diffdbname, 0666)) {  
             &print_error("(dbmopen) $diffdbname が作れません。");  
306          }          }
307            &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});
308            my $fragment = '';
309            $fragment .= qq(;after_edit_cmd=@{[&encode($form{after_edit_cmd})]}) if $form{after_edit_cmd};
310            if ($form{__comment_anchor_index}) {
311                $fragment .= qq(#anchor-$form{__comment_anchor_index});
312            } elsif ($form{__wikiform_anchor_index}) {
313                $fragment .= qq(#wikiform-$form{__wikiform_anchor_index});
314            }
315            &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));
316            &print_message(&Resource('Error:SavedSuccessfully'));
317            &print_content(&Resource('Error:ContinueReading')." @{[&armor_name($form{mypage})]}");
318            &print_footer('CompletedSuccessfully');
319      } else {      } else {
320          if (!tie(%diffbase, "YukiWikiDB", $diffdbname)) {          #&send_mail_to_admin($form{mypage}, "Delete");
321              &print_error("(tie error)");          delete $database{$form{mypage}};
322            delete $infobase{$form{mypage}};
323            if ($form{mytouch}) {
324                &update_recent_changes;
325          }          }
326            &print_header($form{mypage}, -noindex => 1);
327            &print_message(&Resource('Error:PageIsDeletedSuccessfully'));
328            &print_footer($form{mypage});
329      }      }
330  }  }
331    
332  sub closediff {  sub get_search_result ($;%) {
333      if ($dbmopen) {    my $word = lc shift;
334          dbmclose(%diffbase);    my %option = @_;
335      } else {    my @r;
336          untie(%diffbase);    foreach my $page (keys %database) {
337      }      next if !$option{-match_myself} && ($page eq $word);
338  }      my $content = lc $database{$page};
339        if (index (lc $page, $word) > -1) {
340  # フォームからの情報を連想配列 %form に入れる        my $c = $content =~ s/\Q$word\E//g;
341  # &init_form('euc');        push @r, [$page, $c+20];
342  sub init_form {      } elsif (index ($word, lc $page) > -1) {
343      my ($charcode) = @_;        my $c = $content =~ s/\Q$word\E//g;
344      my $query;        push @r, [$page, $c+10];
345      if ($ENV{REQUEST_METHOD} =~ /^post$/i) {      } elsif (my $c = $content =~ s/\Q$word\E//g) {
346          read(STDIN, $query, $ENV{CONTENT_LENGTH});        push @r, [$page, $c];
347      } else {      }
348          $query = $ENV{QUERY_STRING};    }
349      }    #my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#gi; $s };
350      my @assocarray = split(/[&;]/, $query);    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;
351      foreach my $assoc (@assocarray) {    $r = qq|<ul class="search-result">$r</ul>| if $r;
352          my ($property, $value) = split(/=/, $assoc);    wantarray? ($r, scalar @r): $r;
353          $value =~ tr/+/ /;  }
354          $value =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;  
355          &jcode::convert(\$value, $charcode);  sub do_random_jump {
356          $form{$property} = $value;    my @list = keys %database;
357      }    my $name = &encode ($list[rand @list]);
358      my $scheme = 'http';
359      $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
360      print "Location: $scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi?$name\n";
361      print "\n";
362  }  }
363    
 # エラーページを出力する  
364  sub print_error {  sub print_error {
365      my ($msg) = @_;      my ($msg) = @_;
366      &print_header('Error');      &print_header($ErrorPage, -noindex => 1);
367      print "<h1>$IconTag$msg</h1></body></html>";      print qq(<p><strong class="error">$msg</strong></p>);
368        &print_footer($ErrorPage);
369      exit(0);      exit(0);
370  }  }
371    
372  sub escape {  sub print_header ($;%) {
373      my ($line) = shift;      my ($page, %option) = @_;
374      $line =~ s|<|&lt;|g;      my @head;
375      $line =~ s|>|&gt;|g;      $option{body_class} = &is_frozen($page) ? 'frozen' : 'normal';
376      $line =~ s|"|&quot;|g;      $option{body_class} .= " wiki-page-obsoleted" if $option{-content_format} =~ /obsoleted="yes"/;
377      # $line =~ s|\&|&amp;|g;      if ($option{-goto}) {
378      return $line;        if ($UA =~ m#Opera|MSIE 2\.#) {
379  }            ## WARNING: This code may output unsafe HTML document if
380              ##          $option{-goto} is not clean.
381  sub inline {            $option{-goto} =~ tr/;/&/ if $UA =~ m#Opera#;
382      my ($line) = shift;            print qq{Refresh: 0; url=$option{-goto}\n};
383      $line = &escape($line);            push @head, qq(<meta http-equiv="refresh" content="0; url=$option{-goto}">);
384      $line =~ s|'''([^']+?)'''|<strong>$1</strong>|g;        } else {
385      $line =~ s|''([^']+?)''|<em>$1</em>|g;                      $option{-goto} =~ tr/;/&/ if $UA =~ m#Mozilla/[1-4]\.#;
386      $line =~ s!            print qq{Refresh: 0; url="$option{-goto}"\n};
387         (            push @head, qq(<meta http-equiv="refresh" content="0; url=&quot;@{[&escape($option{-goto})]}&quot;">);
388           (?:&lt;(?:mailto|http|https|ftp|urn):[\x21-\x7E]*)&gt;        }
389         | (?:$WikiName)                         # LocalLinkLikeThis      }
390         | (?:$BracketName)                      # [[日本語リンク]]      print qq{Last-Modified: @{[scalar gmtime $option{-last_modified}]}\n} if $option{-last_modified};
391         )      if ($option{-expires}) {
392              !        print qq{Expires: @{[scalar gmtime $option{-expires}]}\n};
393                  &make_link($1)      }
394              !gex;      if ($UA =~ m#Mozilla/2#) {
395      return $line;          my $ct = qq{text/html; charset=@{[&get_charset_name($kanjicode,compatible=>1)]}};
396  }          print qq{Content-Type: $ct\n};
397            push @head, qq{<meta http-equiv="content-type" content="$ct">};
398  # ページのタイトルからページの内容を得る      } elsif ($UA =~ m#Infomosaic#) {
399  sub get_page {          print qq{Content-Type: text/html\n};
400      my $page_name = shift;      } else {
401      return $database{$page_name};          print qq{Content-Type: text/html; charset=@{[&get_charset_name($kanjicode)]}\n};
 }  
   
 # ページの内容を与える  
 # &set_page($title, $txt)  
 sub set_page {  
     # ページを更新する  
     my $title = $_[0];  
     $database{$title} = $_[1];  
     # 空ページなら削除する  
     unless ($database{$title}) {  
         delete $database{$title};  
     }  
     # RecentChangesを更新する  
     my $delim = ' - ';  
     my @pages = split(/\n/, $database{$whatsnew});  
     my $datestr = &get_current_datestr;  
     unshift(@pages, qq|-$datestr$delim$title|);  
     # 同一ページの更新は最新のもののみにし、  
     # 存在しないページはスキップする。  
     my %count;  
     my @newpages;  
     foreach my $line (@pages) {  
         my ($prefix, $title) = split(/$delim/, $line);  
         $count{$title}++;  
         if ($count{$title} == 1 and exists($database{$title})) {  
             push(@newpages, qq|$prefix - $title|);  
         }  
402      }      }
403      # ここで本当に更新      push @head, qq(<title>@{[&escape($page)]}</title>);
404      $database{$whatsnew} = join("\n", splice(@newpages, 0, $maxnew));      if ($UA !~ m#Mozilla/[1-4]\.# || $UA =~ m#MSIE (?:[4-9]\.|\d\d)#) {
405  }        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))]}");
406        }
407  # ページのヘッダを出力      push @head, q(<meta name="ROBOTS" content="NOINDEX">) if $option{-noindex};
408  sub print_header {      my ($Links, $links) = &make_navigate_links ($page);
409      my $title = shift;      #print $Links;      ## Link: fields
410        $links = join "\n", (@head, $links);
411      print <<"EOD";      print <<"EOD";
412  Content-type: text/html  Content-Language: $lang
413    Content-Style-Type: text/css
414    
415  <html><head>  <!-- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
416  <title>$title</title>  "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->
417  <style type="text/css">  <html lang="$lang" class="$option{body_class}">
418  $style  <head profile="http://suika.fam.cx/~wakaba/-temp/wiki/wiki?WikiHTMLMetaProfile">
419  </style>  $links
420  </head>  </head>
421  <body>  <body class="$option{body_class}">
422    EOD
423        &print_navigate_links ($page);
424        print <<EOD;
425    <h1 class="header">@{[&escape($page)]}</h1>
426  EOD  EOD
427  }  }
428    
429  # ツールバーを出力  sub get_charset_name ($;%) {
430  sub print_toolbar {      my ($charset, %option) = (lc shift, @_);
431      my $page_name = shift;      if ($charset =~ 'euc') {
432      my $percent_name = &encode_percent($page_name);          $charset = $option{compatible} ? 'x-euc-jp' : 'euc-jp';
433      my $editlink = '';      } elsif ($charset =~ 'sjis' || $charset =~ 'shift') {
434      if ($page_name ne '' and &is_editable($page_name)) {          $charset = $option{compatible} ? 'x-sjis' : 'shift_jis';
435          $editlink = <<"EOD";      } elsif ($charset =~ 'jis') {
436  <a href="$thisurl?mycmd=edit;mypage=$percent_name">編集</a> |          $charset = 'iso-2022-jp';
437  <a href="$thisurl?mycmd=diff;mypage=$percent_name">差分</a> |      }
438  EOD      $charset;
439    }
440    
441    sub print_navigate_links (@) {
442      my ($page) = @_;
443      my $editable = (&is_editable($page) && !&is_frozen($page)) ? 1 : 0;
444      my $cookedpage = &encode($page);
445      print <<EOH;
446    <div class="tools">
447        @{[ $editable
448            ? qq(<a title="@{[&Resource('EditThisPageLong',escape=>1)]}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E" class="wiki-cmd">@{[&Resource('EditThisPage',escape=>1)]}</a> | )
449            : qq()
450        ]}
451        <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> |
452        <a href="$url_cgi?mycmd=map;mypage=$cookedpage" class="wiki-cmd" title="@{[&Resource('ShowMapOfThisPageLong',escape=>1)]}">@{[&Resource('ShowMapOfThisPage',escape=>1)]}</a> |
453        <a href="$url_cgi?$CreatePage" class="wiki" title="@{[&Resource('GoToCreatePageLong',escape=>1)]}">@{[&Resource('GoToCreatePage',escape=>1)]}</a> |
454        <a href="$url_cgi?$IndexPage" class="wiki" title="@{[&Resource('GoToIndexPageLong',escape=>1)]}">@{[&Resource('GoToIndexPage',escape=>1)]}</a> |
455        <a href="$url_cgi?$FrontPage" class="wiki" title="@{[&Resource('GoToHomePageLong',escape=>1)]}">@{[&Resource('GoToHomePage',escape=>1)]}</a> |
456        <a href="$url_cgi?$SearchPage" class="wiki" title="@{[&Resource('GoToSearchPageLong',escape=>1)]}">@{[&Resource('GoToSearchPage',escape=>1)]}</a> |
457        <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> |
458        <a href="$url_cgi?RecentChanges" class="wiki" title="@{[&Resource('GoToRecentChangesLong',escape=>1)]}">@{[&Resource('GoToRecentChanges',escape=>1)]}</a>
459    </div>
460    EOH
461    }
462    
463    sub make_navigate_links ($) {
464        my $page = shift;
465        my @link;
466        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);
467        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);
468        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')};
469        push @link, {rel=>'myself', href=>"$url_cgi?@{[&encode($page)]}", class=>'wiki', title=>&Resource('GoToMyselfLink')};
470        push @link, {rel=>'index', href=>"$url_cgi?$IndexPage", class=>'wiki', title=>&Resource('GoToIndexPageLink')};
471        push @link, {rel=>'home', href=>"$url_cgi?$FrontPage", class=>'wiki', title=>&Resource('GoToHomePageLink')};
472        push @link, {rel=>'News', href=>"$url_cgi?WikiNews", class=>'wiki', title=>&Resource('GoToWikiNewsLink')};
473        push @link, {rel=>'News', href=>"$url_cgi?RecentChanges", class=>"wiki", title=>&Resource('GoToRecentChangesLink')};
474        push @link, {rel=>'News', href=>"$url_cgi?$RssPage", class=>"wiki", title=>&Resource('GoToRssPageLink'), type=>'application/xml'};
475        push @link, {rel=>'search', href=>"$url_cgi?$SearchPage", class=>'wiki', title=>&Resource('GoToSearchPageLink')};
476        push @link, {rel=>'help', href=>"$url_cgi?WikiHelp", class=>'wiki', title=>&Resource('GoToWikiHelpLink')};
477        push @link, {rel=>'copyright', href=>"$url_cgi?WikiPageLicense", class=>'wiki', title=>&Resource('GoToWikiPageLicenseLink')};
478        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')};
479        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')};
480        push @link, {rel=>'lucky', href=>"$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}", class=>'wiki randomlink', title=>&Resource('GoSomewhereLink')};
481        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};
482        push @link, {rel=>'history', href=>"$url_cgi?mycmd=diff;mypage=@{[&encode($page)]}", title=>&Resource('ViewDiffOfThisPageLink'), class=>'wiki-command'};
483        push @link, {rel=>'contents', href=>"$url_cgi?mycmd=map;mypage=@{[&encode($page)]}", title=>&Resource('ShowMapOfThisPageLink'), class=>'wiki-command'};
484        my ($Links, $links) = ('', '');
485        for my $e (@link) {
486            $links .= qq(<link);
487            $Links .= qq(Link: <$e->{href}>);
488            for my $attr (qw/rel rev href title class type hreflang charset/) {
489                $links .= qq( $attr="@{[&escape($e->{$attr})]}") if $e->{$attr};
490            }
491            for my $attr (qw/rel rev title/) {
492                $Links .= qq(; $attr="@{[do{$e->{$attr} =~ s/([\\\"])/\\$1/g; $e->{$attr}}]}") if $e->{$attr};
493            }
494            $links .= qq(>\n);
495            $Links .= qq(\n);
496      }      }
497      print <<"EOD";      wantarray ? ($Links, $links) : $Links;
 <p>  
  [  
 <a href="$thisurl?mycmd=read;mypage=$toppage">トップ</a> |  
 <a href="$thisurl?mycmd=list">一覧</a> |  
 $editlink  
 <a href="$thisurl?mycmd=search">単語検索</a> |  
 <a href="$thisurl?mycmd=read;mypage=$whatsnew">最終更新</a>  
  ]  
 </p>  
 EOD  
498  }  }
499    
 # ページのフッタを出力  
500  sub print_footer {  sub print_footer {
501      print <<"EOD";      my ($page, $lm) = @_;
502  <address>      my $epage = &encode ($page);
503  <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> 1.6.6 Copyright (C) 2000,2001 by <a href="http://www.hyuki.com/">Hiroshi Yuki.</a>    my $cvslog1 = q$Revision$;
504  + <a href="$modifierlink">$modifier</a> ${version}.    my $cvslog2 = q$Date$;
505  [<a href="/" title="このサーバーの首頁">/</a>    print_navigate_links ($page);
506  <a href="/map" title="このサーバーの案内">地図</a>    print <<"EOD";
507  <a href="/search/" title="このサーバーの検索">検索</a>]  @{[ $lm ? qq(<div id="wikipage-last-modified">@{[&Resource('LastModified=',escape=>1)]}@{[&_rfc3339_date ($lm)]}</div>) : '' ]}
508  </address>  <div class="footer">
509  </body></html>  <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>
510    <a href="/gate/cvs/wakaba/wiki/" title="@{[&Resource('About:SuikaWiki:JumpToCVS',escape=>1)]} ($cvslog2)">@{[&Resource('About:Name:SuikaWiki',escape=>1)]} $cvslog1</a>
511    </div>
512    </body>
513    </html>
514  EOD  EOD
515  }  }
516    
517  # URLやページの名前からリンクを作る  sub escape {
518  sub make_link {      my $s = shift;
519      my $name = shift;      $s =~ s|\r\n|\n|g;
520      $name =~ s/^&lt;(.*)&gt;$/$1/;      $s =~ s|&|&amp;|g;
521      if ($name =~ /^(http|https|ftp).*?(\.png|\.jpeg|\.jpg)?$/) {      $s =~ s|<|&lt;|g;
522          if ($2) {      $s =~ s|>|&gt;|g;
523              return qq|<a href="$name"><img border="0" src="$name" /></a>|;      $s =~ s|"|&quot;|g;
524          } else {      return $s;
525              return qq|&lt;<a href="$name">$name</a>&gt;|;  }
526          }  
527      } elsif ($name =~ /^mailto:(.*)/) {  sub unescape {
528          my $address = $1;      my $s = shift;
529          return qq|&lt;<a href="$name">$address</a>&gt;|;      # $s =~ s|\n|\r\n|g;
530      } elsif ($name =~ /^urn:[0-9A-Za-z_:-]+/) {      $s =~ s|&lt;|<|g;
531          return qq|&lt;<a href="/uri-res/N2L?${name}">$name</a>&gt;|;      $s =~ s|&gt;|>|g;
532      } elsif ($database{$name}) {      $s =~ s|&quot;|"|g;
533          my $percent_name = &encode_percent($name);      $s =~ s|&amp;|&|g;
534          return qq|<a href="$thisurl?mycmd=read;mypage=$percent_name">$name</a>|;      return $s;
535      } else {  }
536          my $percent_name = &encode_percent($name);  
537          return qq|$name<a href="$thisurl?mycmd=edit;mypage=$percent_name">?</a>|;  sub print_content ($;$) {
538      }      my ($rawcontent, %option) = @_;
539  }      print &text_to_html($rawcontent, toc=>1, %option);
540    }
541  # %xx の形式にエンコードする  
542  # これは、  sub text_to_html {
543  # http://www.hyuki.com/yukiwiki/yukiwiki.cgi?mycmd=read&mypage=%3C%8C%8B%8F%E9%8D_%3E      my ($txt, %option) = @_;
544  # という形式のために使われる。      my @toc;
545  # '<結城浩>' → '%3C%8C%8B%8F%E9%8D_%3E'      my @toc2 = @{$option{-toc}||[]};
546  sub encode_percent {      my $tocnum = 0;
547      my $name = shift;      
548      my $encoded = '';      ## Load constants
549      foreach my $ch (split(//, $name)) {      my %const;
550          if ($ch =~ /[A-Za-z0-9_]/) {      if ($option{content_format} =~ /import="([^"]+)"/) {
551              $encoded .= $ch;        for (split /\s*,\s*/, $1) {
552          } else {          my $wp = $database{$_};
553              $encoded .= '%' . sprintf("%02X", ord($ch));          if ($wp =~ m!^\#\?SuikaWikiConst/1.0!) {
554              wiki::suikawikiconst::to_hash ($wp => \%const);
555          }          }
556          }
557      }      }
558      return $encoded;      
559  }      $txt =~ s{__&&([^&]+)&&__}{defined $const{$1}?$const{$1}:qq(__&&$1&&__)}ge;
   
 # テキスト本体をHTMLに変換する  
 sub convert_html {  
     my ($txt) = shift;  
560      my (@txt) = split(/\n/, $txt);      my (@txt) = split(/\n/, $txt);
561        my (@saved, @result);
562        unshift(@saved, "</p>");
563        push(@result, "<p>");
564      foreach (@txt) {      foreach (@txt) {
565          chomp;          chomp;
566          if (/^\*\*(.*)/) {          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
567              push(@result, splice(@saved), '<h3>' . &inline($1) . '</h3>');              push(@toc, qq(----- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
568          } elsif (/^\*(.*)/) {              push(@result, splice(@saved), qq(<h6 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h6>');
569              push(@result, splice(@saved), '<h2>' . &inline($1) . '</h2>');              $tocnum++;
570          } elsif (/^----/) {          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
571              push(@result, splice(@saved), '<hr>');              push(@toc, qq(---- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
572          } elsif (/^(-{1,3})(.*)/) {              push(@result, splice(@saved), qq(<h5 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h5>');
573              &back_push('ul', length($1));              $tocnum++;
574              push(@result, '<li>' . &inline($2) . '</li>');          } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
575                push(@toc, qq(--- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
576                push(@result, splice(@saved), qq(<h4 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h4>');
577                $tocnum++;
578            } elsif (/^\*\*([^\x0D\x0A]*)/) {
579            # if (/^\*\*(.*)/) {
580            # Walrus mod (6) end
581                push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
582                push(@result, splice(@saved), qq(<h3 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h3>');
583                $tocnum++;
584            } elsif (/^\*([^\x0D\x0A]*)/) {
585                push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
586                push(@result, splice(@saved), qq(<h2 @{[&id_and_name("i$tocnum")]}>) . &inline($1, const => \%const) . '</h2>');
587                $tocnum++;
588            } elsif (/^(={1,6})(.*)/) {
589                &back_push('ol', length($1), \@saved, \@result);
590                push(@result, '<li>' . &inline($2, const => \%const) . '</li>');
591            } elsif (/^(-{1,6})(.*)/) {
592              &back_push('ul', length($1), \@saved, \@result);
593              my ($pf, $l) = ('', $2);
594              if (!$main::_EMBEDED && $l =~ s/^\s*\[([0-9]+)\]//) {
595                my $num = 0+$1;
596                $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
597              }
598              push(@result, '<li>' . $pf . &inline ($l, const => \%const) . '</li>');
599          } elsif (/^:([^:]+):(.*)/) {          } elsif (/^:([^:]+):(.*)/) {
600              &back_push('dl', 1);              &back_push('dl', 1, \@saved, \@result);
601              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');              push(@result, '<dt>' . &inline($1, const => \%const) . '</dt>', '<dd>' . &inline($2, const => \%const) . '</dd>');
602          } elsif (/^(>{1,3})(.*)/) {          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
603              &back_push('blockquote', length($1));              &back_push('blockquote', length($1), \@saved, \@result);
604              push(@result, &inline($2));              push @result, "<p>";
605                push(@result, &inline($2, const => \%const));
606                unshift @saved, "</p>";
607          } elsif (/^\s*$/) {          } elsif (/^\s*$/) {
608              push(@result, splice(@saved));              push(@result, splice(@saved));
             unshift(@saved, "</p>");  
609              push(@result, "<p>");              push(@result, "<p>");
610                unshift(@saved, "</p>");
611          } elsif (/^(\s+.*)$/) {          } elsif (/^(\s+.*)$/) {
612              &back_push('pre', 1);              &back_push('pre', 1, \@saved, \@result);
613              push(@result, &escape($1)); # Not &inline, but &escape              push(@result, &inline($1, const => \%const));
614            } elsif (/^\,(.*?)[\x0D\x0A]*$/) {
615                &back_push('table', 1, \@saved, \@result);
616                #######
617                # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.
618                # XXXXX
619                my $tmp = "$1,";
620                my @value = map {/^"(.*)"$/ ? scalar($_ = $1, s/""/"/g, $_) : $_} ($tmp =~ /("[^"]*(?:""[^"]*)*"|[^,]*),/g);
621                my @align = map {(s/^\s+//) ? ((s/\s+$//) ? ' align="center"' : ' align="right"') : ''} @value;
622                my @colspan = map {($_ eq '==') ? 0 : 1} @value;
623                for (my $i = 0; $i < @value; $i++) {
624                    if ($colspan[$i]) {
625                        while ($i + $colspan[$i] < @value and $value[$i + $colspan[$i]] eq '==') {
626                            $colspan[$i]++;
627                        }
628                        $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
629                        $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i], const => \%const));
630                    } else {
631                        $value[$i] = '';
632                    }
633                }
634                push(@result, join('', '<tr>', @value, '</tr>'));
635                # XXXXX
636                #######
637            } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
638                push @result, splice (@saved), '<'.lc($1).'>';
639                unshift @saved, "</p>";
640                push @result, "<p>";
641            } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
642                push @result, splice (@saved), '</'.lc($1).'>';
643            } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
644              my $num = 0+$1;
645              push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
646              push @result, &inline ($2, const => \%const);
647          } else {          } else {
648              push(@result, &inline($_));              push(@result, &inline($_, const => \%const));
649          }          }
650      }      }
651      push(@result, splice(@saved));      push(@result, splice(@saved));
652      return join("\n", @result);      
653        my $toc = '';
654        if ($option{toc}) {
655            # Convert @toc (table of contents) to HTML.
656            # This part is taken from Makio Tsukamoto's WalWiki.
657            my (@tocsaved, @tocresult);
658            foreach (@toc,@toc2) {
659                if (/^(-{1,6})(.*)$/) {
660                    &back_push('ul', length($1), \@tocsaved, \@tocresult);
661                    push(@tocresult, '<li>' . $2 . '</li>');
662                }
663            }
664            push(@tocresult, splice(@tocsaved));
665            $toc = join("\n", @tocresult);
666            $toc = $toc ? qq(<div id="wikipage-toc">$toc</div>) : '';
667        }
668        $toc .= join("\n", @result);
669        $toc =~ s#<p>\n</p>##g;
670        $toc =~ s#[\x0D\x0A]+</#</#g;
671        $toc =~ s#<pre>\n#<pre>#g;
672        $toc;
673  }  }
674    
 # &back_push($tag, $count)  
 # $tagのタグを$levelレベルまで詰める。  
675  sub back_push {  sub back_push {
676      my ($tag, $level) = @_;      my ($tag, $level, $savedref, $resultref, $attr) = @_;
677      while (@saved > $level) {      while (@$savedref > $level) {
678          push(@result, shift(@saved));          push(@$resultref, shift(@$savedref));
679      }      }
680      if ($saved[0] ne "</$tag>") {      if ($savedref->[0] ne "</$tag>") {
681          push(@result, splice(@saved));          push(@$resultref, splice(@$savedref));
682      }      }
683      while (@saved < $level) {      while (@$savedref < $level) {
684          unshift(@saved, "</$tag>");          unshift(@$savedref, "</$tag>");
685          push(@result, "<$tag>");          push(@$resultref, "<$tag$attr>");
686      }      }
687  }  }
688    
689  # 編集可能ページか?  sub inline ($;%) {
690  sub is_editable {      my ($line, %option) = @_;
691      my ($pagename) = @_;      $line = &escape($line);
692      foreach (@uneditable) {      $line =~ s{$embed_command{form}}{&make_custom_form ($1, $2, $3, $4)}ge;
693          if ($pagename eq $_) {      $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;
694              return 0;      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
695          }      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
696        $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;
697        $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
698        $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;
699        $line =~ s%\[Q\[([^]]+)\](?: \[&lt;([\x21-\x5A\x5E-\x7E]+)&gt;\])?\]%「<q@{[$2?qq( cite="$2"):'']}>$1</q>」%g;
700        $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
701        $line =~ s|''([^']+)''|<em>$1</em>|g;
702        $line =~ s{
703          (\[\[(\#\S+?)\]\])
704          |\[\[([^[]+?)](?:&gt;&gt;([0-9]+))?]
705          |&gt;&gt;([0-9]+)
706          |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
707        }{
708          my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
709          if ($l) {
710            return &embedded_to_html($1);
711          } elsif (defined $page) {
712            &make_wikilink ($page, anchor => 0+$anchor);
713          } elsif ($anum) {
714            qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
715          } elsif ($uri) {
716            &make_urilink ($uri);
717          }
718        }gex;
719        return $line;
720    }
721    
722    sub make_wikilink ($%) {
723      my ($ename, %option) = @_;
724      my $name = &unescape ($ename);
725      if ($database{$name}) {
726        my $subject = &escape (&get_subjectline ($name, delimiter => ''));
727        if ($option{anchor}) {
728          return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
729        } else {
730          return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}" class="wiki">$ename</a>);
731      }      }
732      if (&is_valid_name($pagename)) {    } else {
733          return 1;      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>);
734      }
735    }
736    
737    sub make_urilink ($;%) {
738      require URI;
739      my $uri = shift;
740      if ($uri =~ s/^IW://) {       ## InterWiki (not URI)
741        $uri = &unescape ($uri);
742        if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
743          my ($site, $name) = ($1, $2);
744          for ($site, $name) {
745            if (s/^"//) { s/"$//; s/\\(.)/$1/g }
746          }
747          &init_InterWikiName () unless $interwiki{'[[]]'};
748          if ($interwiki{$site}) {
749            &load_formatter ('interwiki');
750            my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
751            $site = &escape ($site); $name = &escape ($name);
752            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;);
753          } else {
754            qq(&lt;@{[&Resource('Error:UnknownInterWikiName=',escape=>1)]}@{[&escape ($site)]}&gt;);
755          }
756        } else {
757          qq(&lt;@{[&Resource('Error:InvalidInterWiki=',escape=>1)]}@{[&escape($uri)]}&gt;);
758      }      }
759      return 0;    } elsif ($uri =~ /^urn:/) {   ## URN
760        my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
761        qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
762      } elsif ($uri =~ s/^MAIL://) {        ## mail address (not URI)
763        my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
764        qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
765      } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) {   ## image (not URI itself)
766        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
767        qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
768      } else {      ## misc. URI
769        CGI::Carp::warningsToBrowser (0);
770        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
771        CGI::Carp::warningsToBrowser (1);
772        qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
773      }
774    }
775    
776    {my $FormIndex = 0;
777    sub make_custom_form ($$$$) {
778        my ($wfname, $definition, $template, $option) = @_;
779        ## $template and $option is currently not used in this procedure.
780        unless ($main::_EMBEDED) {
781            $FormIndex++;
782            if (length $definition) {
783                my $param = bless {}, 'SuikaWiki::Plugin';
784                my $lastmodified = &get_info($form{mypage}, $info_LastModified);
785                &load_formatter (qw/form_input form_option/);
786                $definition = &unescape ($definition);
787                $definition =~ s/\\(.)/$1/g;
788                $option = &unescape ($option);
789                $option =~ s/\\(.)/$1/g;
790                $fmt{form_option}->replace ($option, $param);
791                $param->{output}->{form} = 1 unless defined $param->{output}->{form};
792                $definition .= ' %submit;' if $definition !~ /%submit/ && !$param->{output}->{nosubmit} && $param->{output}->{form};
793                my $target_page = $param->{output}->{page} || $form{mypage};
794                $param->{form_disabled} = 1 if $fixedpage{$target_page};
795                my $target_form = $param->{output}->{id};
796                my $r = '';
797                $r = <<EOH if $param->{output}->{form};
798    <form method="post" action="$url_cgi" id="wikiform-$FormIndex" class="wikiform">
799      <input type="hidden" name="mycmd" value="@{[$param->{form_disabled}?'read':'wikiform']}">
800      <input type="hidden" name="mypage" value="@{[&escape($target_page)]}">
801      <input type="hidden" name="myLastModified" value="$lastmodified">
802      <input type="hidden" name="mytouch" value="on">
803      <input type="hidden" name="@{[$target_form? qq(wikiform_targetform" value="@{[&escape($target_form)]}) : qq(wikiform_index" value="$FormIndex)]}">
804    EOH
805                $r .= qq(<a name="wikiform-$FormIndex"></a>) if $UA =~ m#Mozilla/[12]\.#;
806                $r .= $fmt{form_input}->replace ($definition, $param);
807                $r .= "</form>\n" if $param->{output}->{form};
808                $r;
809           } else {  ## No input-interface WikiForm
810               qq(<a id="wikiform-$FormIndex" name="wikiform-$FormIndex"><!-- #form --></a>);
811           }
812        } else {
813            qq(<ins class="wiki-error">@{[&Resource('Error:WikiForm:EmbedIsNotSupported',escape=>1)]}</ins>);
814        }
815    }}
816    
817    sub print_message {
818        my ($msg) = @_;
819        print qq(<p><strong>@{[&escape($msg)]}</strong></p>);
820  }  }
821    
822  # Validな名前か?  sub init_form {
823  sub is_valid_name {      ## TODO: Support multipart/form-data
824      my ($pagename) = @_;      my $query = '';
825      if ($pagename =~ /^$WikiName$/) {      if (uc $main::ENV{REQUEST_METHOD} eq 'POST') {
826          return 1;        read STDIN, $query, $main::ENV{CONTENT_LENGTH};
827      } elsif ($pagename =~ /^$BracketName$/) {      }
828          return 1;      $query .= ($query ? ';' : '') . $main::ENV{QUERY_STRING};
829        if ($main::ENV{REQUEST_METHOD} ne 'POST' && $main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;=]/) {
830          my $query = &decode($main::ENV{QUERY_STRING});
831          $query = &code_convert(\$query, $kanjicode);
832          if ($page_command{$query}) {
833            $form{mycmd} = $page_command{$query};
834            $form{mypage} = $query;
835          } else {
836            $form{mypage} = $query;
837            $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';
838          }
839      } else {      } else {
840          return 0;        for (split /[;&]/, $query) {
841            if (my ($n, $v) = split /=/, $_, 2) {
842              for ($n, $v) {tr/+/ /; s/%([0-9A-Fa-f][0-9A-Fa-f])/pack 'C', hex $1/ge};
843              $form{$n} = $v;
844            }
845          }
846          if ($page_command{$form{mypage}} && $form{mycmd} eq 'read') {
847            $form{mypage} = &code_convert(\$form{mypage}, $kanjicode);
848            $form{mycmd} = $page_command{$form{mypage}};
849          }
850        }
851        $form{mypage} ||= 'HomePage';
852        $form{mycmd} ||= 'read';
853    
854        # mypreview_edit        -> do_edit, with preview.
855        # mypreview_adminedit   -> do_adminedit, with preview.
856        # mypreview_write       -> do_write, without preview.
857        foreach (keys %form) {
858            if (/^mypreview_(.*)$/) {
859                $form{mycmd} = $1;
860                $form{mypreview} = 1;
861            }
862      }      }
 }  
863    
864  # 現在時刻の文字列を得る      #
865  sub get_current_datestr {      # $form{mycmd} is frozen here.
866      my (@wdays) = ( "日", "月", "火", "水", "木", "金", "土" );      #
867      my ($sec, $min, $hour, $mday, $mon, $year, $wday) = localtime(time);  
868      return sprintf("%4d-%02d-%02d (%s) %02d:%02d:%02d",      for (grep /^wikiform__/, keys %form) {
869          $year + 1900, $mon + 1, $mday, $wdays[$wday], $hour, $min, $sec);          $form{$_} = &code_convert (\$form{$_}, $kanjicode);
870  }      }
871        $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
872  # URL?SomePageや、      $form{myname} = &code_convert(\$form{myname}, $kanjicode);
873  # URL?[[結城浩]]の形式だった場合、(not yet)  }
874  # 強制的にmycmdをreadにして$formの内容を設定する。  
875  sub normalize_form {  sub update_recent_changes {
876      foreach my $key (keys %form) {      my $update = "- @{[&get_now]} [[$form{mypage}]] @{[&get_subjectline($form{mypage})]}";
877          if ($key =~ /^$WikiName$/) {      my @oldupdates = split(/\x0D?\x0A/, $database{RecentChanges});
878              $form{mycmd} = 'read';      shift @oldupdates; ## '#?' magic line
879              $form{mypage} = $1;      my @updates;
880              last;      foreach (@oldupdates) {
881          } elsif ($key =~ /^$BracketName$/) {          /^\- \d\d\d\d\-\d\d\-\d\d \d\d:\d\d \[\[([^]]+)\]\]/;
882              $form{mycmd} = 'read';          my $name = $1;
883              $form{mypage} = $1;          if ($name ne $form{mypage}) {
884              last;              push @updates, $_;
885          }          }
886      }      }
887        if (&is_exist_page($form{mypage})) {
888          unshift @updates, $update;
889        }
890        splice @updates, (&Resource ('RecentChanges:Max') || 50) + 1;
891        $database{RecentChanges} = "#?SuikaWiki/0.9\n" . join("\n", @updates);
892        if ($file_touch) {
893            open(FILE, "> $file_touch");
894            print FILE localtime() . "\n";
895            close(FILE);
896        }
897  }  }
898    
899  # 変換テストを行なうときのサンプル  {my %SubjectLine;
900  sub print_sample {  sub get_subjectline {
901      my $txt = &convert_html(<<"EOD");      my ($page, %option) = @_;
902  *大見出し1      unless (defined $SubjectLine{$page}) {
903  **小見出し1-1        if (not &is_editable($page)) {
904  -項目1          $SubjectLine{$page} = "";
905  -項目2        } else {
906  -項目3          $SubjectLine{$page} = $database{$page};
907  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1          $SubjectLine{$page} =~ s!^\#\?[^\x0A\x0D]+[\x0A\x0D]*!!s;
908  段落1段落1段落1段落1段落1段落''強調''1段落1段落1段落1段落1段落1          $SubjectLine{$page} =~ s/\x0D?\x0A.*//s;
909  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1        }
910        }
911  段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2      if (length $SubjectLine{$page}) {
912  段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2        $option{delimiter} = defined $option{delimiter} ? $option{delimiter} : &Resource('Title-Summary Delimiter');
913  段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2        $option{delimiter}.$SubjectLine{$page}.$option{tail};
914  **小見出し1-2      } else {
915  :用語1:いろいろ書いた解説文1と''強調単語''        '';
916  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1      }
917  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1  }}
918  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1  
919  :用語2:いろいろ書いた解説文2  sub open_db {
920  :用語3:いろいろ書いた解説文3      if ($modifier_dbtype eq 'dbmopen') {
921  ----          dbmopen(%database, $dataname, 0666) or &print_error("(dbmopen) $dataname");
922  *大見出し2          dbmopen(%infobase, $infoname, 0666) or &print_error("(dbmopen) $infoname");
923  **小見出し2-1      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
924  &lt;http://suika.fam.cx/&gt;          eval q{use AnyDBM_File};
925  **小見出し2-2          tie(%database, "AnyDBM_File", $dataname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $dataname");
926            tie(%infobase, "AnyDBM_File", $infoname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $infoname");
927  [[結城浩]]      } else {
928            eval q{use Yuki::YukiWikiDB};
929  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1          tie(%database, "Yuki::YukiWikiDB", $dataname) or &print_error("(tie Yuki::YukiWikiDB) $dataname");
930  段落1段落1段落1段落'''強調'''1段落1段落1段落1段落1段落1段落1段落1          tie(%infobase, "Yuki::YukiWikiDB", $infoname) or &print_error("(tie Yuki::YukiWikiDB) $infoname");
931  段落1段落1段落1段落'''''強い強調'''''1段落1段落1段落1段落1段落1段落1段落1段落1      }
 >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2  
 >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2  
 >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2  
   
 レベル0レベル0レベル0レベル0レベル0レベル0  
   
 >レベル1  
 >レベル1  
 >レベル1  
 >>レベル2  
 >>レベル2  
 >>レベル2  
 >>>レベル3  
 -はろ1  
 --はろ2  
 ろろろろ2  
 ---はろ3  
 --はろ2  
 ---はろ3  
 --はろ2  
 ---はろ3  
 >>>レベル3  
 >>>レベル3  
 >>>レベル3  
 EOD  
     print $txt;  
     exit;  
932  }  }
933    
934  sub diff_check {  sub close_db {
935      traverse_sequences(      if ($modifier_dbtype eq 'dbmopen') {
936              $msgrefA, $msgrefB,          dbmclose(%database);
937              {          dbmclose(%infobase);
938                  MATCH => \&df_match,      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
939                  DISCARD_A => \&df_delete,          untie(%database);
940                  DISCARD_B => \&df_add,          untie(%infobase);
941              }      } else {
942      );          untie(%database);
943      &diff_flush;          untie(%infobase);
944        }
945  }  }
946    
947  sub diff_flush {  sub open_diff {
948      $diff_text .= join('', map { "-$_\n" } splice(@diff_deleted));      if ($modifier_dbtype eq 'dbmopen') {
949      $diff_text .= join('', map { "+$_\n" } splice(@diff_added));          dbmopen(%diffbase, $diffname, 0666) or &print_error("(dbmopen) $diffname");
950        } elsif ($modifier_dbtype eq 'AnyDBM_File') {
951            tie(%diffbase, "AnyDBM_File", $diffname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $diffname");
952        } else {
953            tie(%diffbase, "Yuki::YukiWikiDB", $diffname) or &print_error("(tie Yuki::YukiWikiDB) $diffname");
954        }
955  }  }
956    
957  sub df_match {  sub close_diff {
958      my ($a, $b) = @_;      if ($modifier_dbtype eq 'dbmopen') {
959      &diff_flush;          dbmclose(%diffbase);
960      $diff_text .= "=$msgrefA->[$a]\n";      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
961            untie(%diffbase);
962        } else {
963            untie(%diffbase);
964        }
965  }  }
966    
967  sub df_delete {  sub print_editform {
968      my ($a, $b) = @_;      my ($mymsg, $lastmodified, %mode) = @_;
969      push(@diff_deleted, $msgrefA->[$a]);      my $frozen = &is_frozen($form{mypage});
970    
971        if ($form{mypreview}) {
972            if ($form{mymsg}) {
973                unless ($mode{conflict}) {
974                    print qq(<h3>@{[&Resource('Preview:Title',escape=>1)]}</h3>\n);
975                    print qq(<p>@{[&Resource('Preview:Notice',escape=>1)]}</p>\n);
976                    print qq(<div class="preview">\n);
977                    &print_content($form{mymsg});
978                    print qq(</div>\n);
979                }
980            } else {
981                print @{[&Resource('Preview:Empty',escape=>1)]};
982            }
983            $mymsg = &escape($form{mymsg});
984        } else {
985            $mymsg = &escape($mymsg || $database{NewPageTemplate});
986        }
987        my $magic = '';
988        $magic = $1 if $mymsg =~ m/^([^\x0A\x0D]+)/s;
989    
990        my $edit = $mode{admin} ? 'adminedit' : 'edit';
991        my $escapedmypage = &escape($form{mypage});
992        my $escapedmypassword = &escape($form{mypassword});
993        my $selected = 'read';
994        if ($form{after_edit_cmd}) {
995            $selected = $form{after_edit_cmd};
996        } elsif ($magic =~ /Const|Config|CSS/) {
997            $selected = 'edit';
998        }
999        my $afteredit = <<EOH;
1000    <select name="after_edit_cmd">
1001    <option value="read" label="@{[&Resource('Edit:SaveAndView',escape=>1)]}"@{[$selected eq 'read' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndView',escape=>1)]}</option>
1002    <option value="edit" label="@{[&Resource('Edit:SaveAndEdit',escape=>1)]}"@{[$selected eq 'edit' ? ' selected="selected"':'']}>@{[&Resource('Edit:SaveAndEdit',escape=>1)]}</option>
1003    </select>
1004    EOH
1005    
1006        print <<"EOD";
1007    <form action="$url_cgi" method="post">
1008    <h2>@{[&Resource('Edit:Title',escape=>1)]}</h2>
1009        @{[ $mode{conflict} ? '' : qq(<input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}"><kbd>S</kbd>) ]}
1010        @{[ $mode{admin} ? qq(<label>@{[&Resource('Edit:Password=',escape=>1)]}<input type="password" name="mypassword" value="$escapedmypassword" size="10"></label>) : "" ]} [@{[do {my $n = 0;
1011                   $mymsg =~ s/(?:-+\s)?\[([0-9]+)\]/$n = $1 if $1 > $n; $&/mge;
1012                   ++$n}]}]<br>
1013        <input type="hidden" name="myLastModified" value="$lastmodified">
1014        <input type="hidden" name="mypage" value="$escapedmypage">
1015        <textarea cols="@{[&Resource('Edit:Form:Cols')+0||80]}" rows="@{[&Resource('Edit:Form:Rows')+0||20]}" name="mymsg" tabindex="1">$mymsg</textarea><br>
1016    @{[
1017        $mode{admin} ?
1018        qq(
1019        <label><input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>@{[&Resource('Edit:Freeze',escape=>1)]}</label>
1020        <label><input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>@{[&Resource('Edit:DontFreeze',escape=>1)]}</label><br>)
1021        : ""
1022    ]}
1023    @{[
1024        $mode{conflict} ? "" :
1025        qq(
1026            <input type="checkbox" name="mytouch" value="on" checked="checked">@{[&Resource('Edit:UpdateTimeStamp',escape=>1)]}<br>
1027            <input type="submit" name="mypreview_$edit" value="@{[&Resource('Edit:Preview',escape=>1)]}">
1028            <input type="submit" name="mypreview_write" value="@{[&Resource('Edit:Save',escape=>1)]}" accesskey="S"><kbd>S</kbd>
1029           $afteredit
1030           <br>
1031        )
1032    ]}
1033    </form>
1034    EOD
1035        unless ($mode{conflict}) {
1036            ## Show help text
1037            my $help = $database{WikiEditHelp};
1038            $help =~ s!^\#\?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1039            print &text_to_html ($help, toc => 0);
1040        }
1041  }  }
1042    
1043  sub df_add {  sub print_passwordform {
1044      my ($a, $b) = @_;          print <<"EOD";
1045      push(@diff_added, $msgrefB->[$b]);  <form action="$url_cgi" method="post">
1046        <input type="hidden" name="mycmd" value="adminchangepassword">
1047        <label>@{[&Resource('Password:Old=',escape=>1)]}<input type="password" name="myoldpassword" size="10"></label><br>
1048        <label>@{[&Resource('Password:New1=',escape=>1)]}<input type="password" name="mynewpassword" size="10"></label><br>
1049        <label>@{[&Resource('Password:New2=',escape=>1)]}<input type="password" name="mynewpassword2" size="10"></label><br>
1050        <input type="submit" value="@{[&Resource('WikiForm:Change',escape=>1)]}"><br>
1051    </form>
1052    EOD
1053  }  }
1054    
1055  sub calc_message_digest {   # You have to use MD5...  sub is_editable {
1056      my $text = shift;      my ($page) = @_;
1057      my @text = split(//, $text);      if ($fixedpage{$page} || $page =~ /\s/ || $page =~ /^\#/) {
1058      my $len = length($text);          return 0;
1059      my $checksum = 0;      } else {
1060      foreach (@text) {          return 1;
         $checksum += ord($_);  
         $checksum = ($checksum * 2) % 65536 + (($checksum & 32768) ? 1 : 0); # 16bit rotate  
1061      }      }
     return "$len:$checksum";  
1062  }  }
1063    
1064  # Definition of YukiWikiDB  # armor_name:
1065  package YukiWikiDB;  #   WikiName -> WikiName
1066    #   not_wiki_name -> [[not_wiki_name]]
1067  my $debug = 1;  sub armor_name { qq([[$_[0]]]) }
1068    
1069    # unarmor_name:
1070    #   [[bracket_name]] -> bracket_name
1071    #   WikiName -> WikiName
1072    sub unarmor_name {
1073        my ($name) = @_;
1074        if ($name =~ /^\[\[(\S+?)\]\]$/) {
1075            return $1;
1076        } else {
1077            return $name;
1078        }
1079    }
1080    
1081  # Constructor  sub decode {
1082  sub new {      my ($s) = @_;
1083      return shift->TIEHASH(@_);      $s =~ tr/+/ /;
1084        $s =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;
1085        return $s;
1086  }  }
1087    
1088  # tying  sub encode {
1089  sub TIEHASH {      my ($s) = @_;
1090      my ($class, $dbname) = @_;      my $encoded = '';
1091      my $self = {      foreach my $ch (split(//, $s)) {
1092          dir => $dbname,          if ($ch =~ /[A-Za-z0-9_]/) {
1093          keys => [],              $encoded .= $ch;
1094      };          } else {
1095      if (not -d $self->{dir}) {              $encoded .= '%' . sprintf("%02X", ord($ch));
         if (!mkdir($self->{dir}, 0777)) {  
             print "mkdir(" . $self->{dir} . ") fail\n" if ($debug);  
             return undef;  
1096          }          }
1097      }      }
1098      return bless($self, $class);      return $encoded;
1099  }  }
1100    
1101  # Store  sub conflict {
1102  sub STORE {      my ($page, $rawmsg) = @_;
1103      my ($self, $key, $val) = @_;      if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {
1104      my $file = &make_filename($self, $key);          return 0;
     if (open(FILE,"> $file")) {  
         binmode(FILE);  
         print FILE $val;  
         close(FILE);  
         return $self->{$key} = $val;  
     } else {  
         print "$file create error.";  
1105      }      }
1106        &print_header($page, -noindex => 1);
1107        &print_content(&Resource('Error:Conflict'));
1108        &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);
1109        &print_footer($page);
1110        return 1;
1111    }
1112    
1113    sub get_now {
1114        my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
1115        $year += 1900;
1116        $mon++;
1117        $mon = "0$mon" if $mon < 10;
1118        $day = "0$day" if $day < 10;
1119        $hour = "0$hour" if $hour < 10;
1120        $min = "0$min" if $min < 10;
1121        #$sec = "0$sec" if $sec < 10;
1122        return "$year-$mon-$day $hour:$min";
1123    }
1124    
1125    sub init_InterWikiName {
1126      my @content = split /\n/, $database{InterWikiName};
1127      for (@content) {
1128        if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
1129          $interwiki{$1} = $2;
1130        }
1131      }
1132      $interwiki{'[[]]'} = 1;       ## dummy
1133  }  }
1134    
1135  # Fetch  
1136  sub FETCH {  sub get_info {
1137      my ($self, $key) = @_;      my ($page, $key) = @_;
1138      my $file = &make_filename($self, $key);      my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1139      if (open(FILE, $file)) {      return $info{$key};
1140          local $/;  }
1141          $self->{$key} = <FILE>;  
1142          close(FILE);  sub set_info {
1143        my ($page, $key, $value) = @_;
1144        my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1145        $info{$key} = $value;
1146        my $s = '';
1147        for (keys %info) {
1148            $s .= "$_=$info{$_}\n";
1149        }
1150        $infobase{$page} = $s;
1151    }
1152    
1153    sub frozen_reject {
1154        my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);
1155        my ($willbefrozen) = $form{myfrozen};
1156        if (not $isfrozen and not $willbefrozen) {
1157            # You need no check.
1158            return 0;
1159        } elsif (valid_password($form{mypassword})) {
1160            # You are admin.
1161            return 0;
1162        } else {
1163            &print_error(&Resource('Error:PasswordIsIncorrect'));
1164            return 1;
1165      }      }
     return $self->{$key};  
1166  }  }
1167    
1168  # Exists  sub valid_password {
1169  sub EXISTS {      my ($givenpassword) = @_;
1170      my ($self, $key) = @_;      my ($validpassword_crypt) = &get_info($AdminSpecialPage, 'AdminPassword');
1171      my $file = &make_filename($self, $key);      if (crypt($givenpassword, $validpassword_crypt) eq $validpassword_crypt) {
1172      return -e($file);          return 1;
1173        } else {
1174            return 0;
1175        }
1176  }  }
1177    
1178  # Delete  sub is_frozen {
1179  sub DELETE {      my ($page) = @_;
1180      my ($self, $key) = @_;      if (&get_info($page, $info_IsFrozen)) {
1181      my $file = &make_filename($self, $key);          return 1;
1182      unlink $file;      } else {
1183      return delete $self->{$key};          return 0;
1184        }
1185  }  }
1186    
1187  sub FIRSTKEY {  sub do_comment {
1188      my ($self) = @_;      my ($content) = $database{$form{mypage}};
1189      opendir(DIR, $self->{dir}) or die $self->{dir};      my $default_name;   ## this code does not strict.
1190      @{$self->{keys}} = grep /\.txt$/, readdir(DIR);      $default_name = $1 if $content =~ /default-name="([^"]+)"/;
1191      foreach my $name (@{$self->{keys}}) {      my $datestr = '[WEAK['.&get_now.']]';
1192          $name =~ s/\.txt$//;      my $namestr = $form{myname} || $default_name || &Resource('WikiForm:WikiComment:DefaultName');
1193          $name =~ s/[0-9A-F][0-9A-F]/pack("C", hex($&))/eg;      ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
1194        if ($namestr =~ /^(?:>>)?[0-9]/) {
1195          $namestr = qq( ''$namestr'': );
1196        } elsif (length $namestr) {
1197          $namestr = qq( ''[[$namestr]]'': );
1198        }
1199        my $anchor = &get_new_anchor_index ($content);
1200        my $i = 1;  my $o = 0;
1201        $content =~ s{(\[\[\#r?comment\]\])}{
1202          my $embed = $1;
1203          if ($i == $form{comment_index}) {
1204            if ($embed ne '[[#rcomment]]') {
1205              $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;
1206            } else {
1207              $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;
1208            }
1209          }
1210          $i++; $embed;
1211        }ge;
1212        unless ($o) {
1213          $content = "#?SuikaWiki/0.9\n\n" unless $content;
1214          $content .= "\n" unless $content =~ /\n$/s;
1215          $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
1216        }
1217        $form{__comment_anchor_index} = $anchor;
1218        if ($form{mymsg} || $form{myname}) {
1219            $form{mymsg} = $content;
1220            $form{mytouch} = 'on';
1221            &do_write;
1222        } else {
1223            $form{mycmd} = 'read';
1224            &do_read;
1225      }      }
     return shift @{$self->{keys}};  
1226  }  }
1227    
1228  sub NEXTKEY {  sub get_new_anchor_index ($) {
1229      my ($self) = @_;      my $content = shift;
1230      return shift @{$self->{keys}};      my $anchor = 0;
1231        $content =~ s/^(?:[-=]+\s*)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
1232        $anchor + 1;
1233    }
1234    
1235    my $CommentIndex = 0;
1236    sub embedded_to_html {
1237        my ($embedded) = @_;
1238        if ($embedded eq '[[#comment]]' or $embedded eq '[[#rcomment]]') {
1239          unless ($main::_EMBEDED) {
1240            my $lastmodified = &get_info($form{mypage}, $info_LastModified);
1241            return <<"EOD";
1242    <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
1243        <input type="hidden" name="mycmd" value="comment">
1244        <input type="hidden" name="mypage" value="$form{mypage}">
1245        <input type="hidden" name="myLastModified" value="$lastmodified">
1246        <input type="hidden" name="mytouch" value="on">
1247        <input type="hidden" name="comment_index" value="$CommentIndex">
1248        @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
1249        <input type="text" name="myname" value="" size="10" class="comment-name">
1250        <input type="text" name="mymsg" value="" size="60" class="comment-msg">
1251        <input type="submit" value="@{[&Resource('WikiForm:Add',escape=>1)]}" title="@{[&Resource('WikiForm:AddLong',escape=>1)]}" class="comment-submit">
1252    </p></form>
1253    EOD
1254         } else {
1255            return <<"EOD";
1256    <del><form action="$url_cgi" method="get">
1257        <input type="hidden" name="mycmd" value="read">
1258        <input type="hidden" name="mypage" value="$form{mypage}">
1259        @{[&Resource('WikiForm:WikiComment:Name=',escape=>1)]}
1260        <input type="text" name="myname" value="" size="10" disabled="disabled">
1261        <input type="text" name="mymsg" value="" size="60" disabled="disabled">
1262    </form></del>
1263    EOD
1264        }
1265      } elsif ($embedded =~ /$embed_command{searched}/) {
1266        return get_search_result ($1, -match_myself => 1);
1267      } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
1268        my ($name, $r) = ($1, '');
1269        if ($main::_EMBEDED != 1) {
1270          my ($content, $cf) = ($database{$name}, 'SuikaWiki/0.9');
1271          $cf = $1 if $content =~ s!^(?:[\#<]\?|/\*\s*)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1272          if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
1273            $main::_EMBEDED = 1;
1274            $r = &text_to_html ($content, content_format => $cf);
1275            $main::_EMBEDED = 0;
1276          } elsif (length $content) {
1277            $r = "<pre>@{[&escape ($content)]}</pre>";
1278          } else {
1279            $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:PageNotFound')]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
1280          }
1281        } else {    ## nested #EMBED
1282          $r = &text_to_html ("[INS[\n[[$name]]: @{[&Resource('Embed:Nested',escape=>1)]}\n]INS]\n", content_format => 'SuikaWiki/0.9');
1283        }
1284        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>);
1285      } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
1286        return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);
1287      } else {
1288        return $embedded;
1289      }
1290    }
1291    
1292    sub load_formatter (@) {
1293        for my $t (@_) {
1294            unless ($fmt{$t}) {
1295                require Message::Util::Formatter;
1296                $fmt{$t} = Message::Util::Formatter->new;
1297                for (@{$SuikaWiki::Plugin::List{'wiki'.$t}||[]}) {
1298                    $_->load_formatter ($fmt{$t}, type => 'wiki'.$t);
1299                }
1300            }
1301        }
1302  }  }
1303    
1304  sub make_filename {  sub do_wikiform {
1305      my ($self, $key) = @_;      my $content = $database{$form{mypage}};
1306      my $enkey = '';      my $anchor = &get_new_anchor_index ($content);
1307      foreach my $ch (split(//, $key)) {      &load_formatter (qw/form_template form_option/);
1308          $enkey .= sprintf("%02X", ord($ch));      my $write = 0;
1309        my $i = 1;
1310        $content =~ s{$embed_command{form}}{
1311            my ($embed, $wfname, $template, $option) = ($&, $1, $3, $4);
1312            if (($wfname && $wfname eq $form{wikiform_targetform})
1313                || $i == $form{wikiform_index}) {
1314                $template =~ s/\\(.)/$1/g;
1315                $option =~ s/\\(.)/$1/g;
1316                my $param = bless {}, 'SuikaWiki::Plugin';
1317                $param->{page} = $form{mypage};
1318                $param->{form_index} = $i;
1319                $param->{form_name} = $wfname;
1320                $param->{anchor_index} = $anchor;
1321                $param->{argv} = \%form;
1322                $param->{default_name} = $1 if $content =~ /default-name="([^"]+)"/;
1323                $param->{default_name} ||= &Resource('WikiForm:WikiComment:DefaultName');
1324                $fmt{form_option}->replace ($option, $param);
1325                my $t = 1;
1326                for (@{$param->{require}||[]}) {
1327                    (undef $t, last) unless length $param->{argv}->{'wikiform__'.$_};
1328                }
1329                $t = $fmt{form_template}->replace ($template, $param) if $t;
1330                if (length $t) {
1331                    if ($param->{output}->{reverse}) {
1332                        $embed .= "\n" . $t;
1333                    } else {
1334                        $embed = $t . "\n" . $embed;
1335                    }
1336                    $write = 1;
1337                    $form{__comment_anchor_index} = $anchor
1338                      if $param->{anchor_index_};  ## $anchor is used!
1339                }
1340                $form{__wikiform_anchor_index} = $i;
1341                undef $form{wikiform_targetform};  ## make sure never to match
1342                undef $form{wikiform_index};       ## with WikiForm in rest of page
1343            }
1344            $i++; $embed;
1345        }ge;
1346        unless ($write) {
1347          #$content = "#?SuikaWiki/0.9\n\n" unless $content;
1348          #$content .= "\n" unless $content =~ /\n$/s;
1349          #
1350        }
1351        if ($write) {
1352            $form{mymsg} = $content;
1353            $form{mytouch} = 'on';
1354            &do_write;
1355        } else {
1356            $form{mycmd} = 'read';
1357            &do_read;
1358      }      }
     return $self->{dir} . "/$enkey.txt";  
1359  }  }
 __END__  
   
 =head1 NAME  
   
 YukiWiki - 自由にページを追加・削除・編集できるWebページ構築CGI  
   
     Copyright (C) 2000,2001 by Hiroshi Yuki.  
     結城浩 <hyuki@hyuki.com>  
     http://www.hyuki.com/  
     http://www.hyuki.com/yukiwiki/  
   
 =head1 SYNOPSIS  
   
     http://www.hyuki.com/yukiwiki/yukiwiki.cgi  
   
 =head1 DESCRIPTION  
   
 YukiWiki(結城ウィキィ)は参加者が自由にページを追加・削除・編集できる  
 不思議なWebページ群を作るCGIです。  
 Webで動作する掲示板とちょっと似ていますが、  
 Web掲示板が単にメッセージを追加するだけなのに対して、  
 YukiWikiは、Webページ全体を自由に変更することができます。  
   
 YukiWikiは、Cunningham & CunninghamのWikiWikiWebの  
 仕様を参考にして独自に作られました。  
   
 YukiWikiはPerlで書かれたCGIスクリプトとして実現されていますので、  
 Perlが動作するWebサーバならば比較的容易に設置できます。  
   
 あとはdbmopenが使える環境ならば設置できます(Version 1.5.0以降ならdbmopenが使えなくても設置できます)。  
   
   
 YukiWikiはフリーソフトです。  
 ご自由にお使いください。  
   
 =head1 設置方法  
   
 =head2 入手  
   
 YukiWikiの最新版は、  
 http://www.hyuki.com/yukiwiki/  
 から入手できます。  
   
 =head2 ファイル一覧  
   
     readme.txt      ドキュメント  
     yukiwiki.cgi    YukiWiki本体  
     yukiwiki.gif    ロゴ(カラー版)  
     yukimono.gif    ロゴ(モノクロ版)  
     jcode.pl        漢字コードライブラリ  
   
 =head2 インストール  
   
 =over 4  
   
 =item 1.  
   
 アーカイブを解く。  
   
 =item 2.  
   
 yukiwiki.cgiのはじめの方にある設定を確認します。  
 通常は何もしなくてよいが、  
 はじめは$touchfileを''にした方がよいでしょう。  
   
 =item 3.  
   
 yukiwiki.cgiとjcode.plを同じところに設置します。  
   
 =item 4.  
   
 サイズ0のyukiwiki.dbというファイルを設置します。  
 (Perlシステムによってはyukiwiki.pag, yukiwiki.dir)  
   
 =item 5.  
   
 yukiwiki.cgiにブラウザからアクセスします。  
   
 =back  
   
 =head2 パーミッション  
   
         ファイル        パーミッション      転送モード  
         yukiwiki.cgi    755                 ASCII  
         yukiwiki.gif    644                 BINARY  
         yukimono.gif    644                 BINARY  
         jcode.pl        644                 ASCII  
   
     $dbmopen = 1; にした場合:  
         yukiwiki.db     666                 BINARY  
         (yukiwiki.pag, yukiwiki.dirの場合もあり)  
   
     $dbmopen = 0; にした場合: (カレントディレクトリを777にしておく)  
         .               777                 (転送しない)  
   
 =head1 データのバックアップ方法  
   
 $dbmopen = 1;の場合は、  
 データはすべてyukiwiki.db(.dir, .pag)に入る。  
 これをバックアップすればよい。  
   
 $dbmopen = 0;の場合は、  
 yukiwikiというディレクトリができるので、  
 これ以下をバックアップすればよい。  
   
 =head1 新しいページの作り方  
   
 =over 4  
   
 =item 1.  
   
 まず、適当なページ(例えばFrontPage)を選び、  
 ページの下にある「編集」リンクをたどります。  
   
 =item 2.  
   
 するとテキスト入力ができる状態になるので、  
 そこにNewPageのような単語  
 (大文字小文字混在している英文字列)  
 を書いて「保存」します。  
   
 =item 3.  
   
 保存すると、FrontPageのページが書き換わり、  
 あなたが書いたNewPageという文字列の後ろに ? というリンクが表示されます。  
 この ? はそのページがまだ存在しないことを示す印です。  
   
 =item 4.  
   
 その ? をクリックすると新しいページNewPageができますので、  
 あなたの好きな文章をその新しいページに書いて保存します。  
   
 =item 5.  
   
 NewPageページができるとFrontPageの ? は消えて、リンクとなります。  
   
 =back  
   
 =head1 テキスト整形のルール  
   
 =over 4  
   
 =item *  
   
 連続した複数行はフィルされて表示されます。  
   
 =item *  
   
 空行は段落C<< <p> >>の区切りとなります。  
   
 =item *  
   
 HTMLのタグは書けません。  
   
 =item *  
   
 B<''ボールド''>のようにシングルクォート二つではさむと、  
 ボールドC<< <b> >>になります。  
   
 =item *  
   
 B<'''イタリック'''>のようにシングルクォート三つではさむと、  
 イタリックC<< <i> >>になります。  
   
 =item *  
   
 B<---->のようにマイナス4つがあると、  
 水平線C<< <hr> >>になります。  
   
 =item *  
   
 行をB<*>ではじめると、  
 大見出しC<< <h2> >>になります。  
   
 =item *  
   
 行をB<**>ではじめると、  
 小見出しC<< <h3> >>になります。  
1360    
1361  =item *  sub code_convert {
1362      require Jcode;
1363  行をマイナス-ではじめると、      my ($contentref, $code) = (shift, shift || $kanjicode);
1364  箇条書きC<< <ul> >>になります。      $code = 'jis' if $code =~ /iso/;
1365  マイナスの数が増えるとレベルが下がります(3レベルまで)      $code = 'euc' if $code =~ /euc/;
1366        $code = 'sjis' if $code =~ /shift/;
1367      -項目1      $code = 'utf8' if $code =~ /utf/;
1368      --項目1-1      #&Jcode::convert($contentref, $code);       # for Jcode.pm
1369      --項目1-2  #    &jcode::convert($contentref, $code);       # for jcode.pl
1370      -項目2      #&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';
1371      -項目3      Jcode->new ($contentref)->h2z->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;
1372      --項目3-1      return $$contentref;
1373      ---項目3-1-1  }
     ---項目3-1-2  
     --項目3-2  
   
 =item *  
   
 コロンを使うと、  
 用語と解説文のリストC<< <dl> >>が書けます。  
   
     :用語1:いろいろ書いた解説文1  
     :用語2:いろいろ書いた解説文2  
     :用語3:いろいろ書いた解説文3  
   
 =item *  
   
 リンク  
   
 =over 4  
   
 =item *  
   
 LinkToSomePageやFrontPageのように、  
 英単語の最初の一文字を大文字にしたものが  
 二つ以上連続したものはYukiWikiのページ名となり、  
 それが文章中に含まれるとリンクになります。  
   
 =item *  
   
 http://www.hyuki.com/ のようなURLは自動的にリンクになります。  
   
 =item *  
   
 二重の大かっこ[[ ]]でくくった文字列も、  
 YukiWikiのページ名になります。  
 大かっこの中にはスペースを含めてはいけません。  
 日本語も使えます。  
   
 =back  
   
 =item *  
   
 行頭がスペースやタブで始まっていると、  
 それは整形済みの段落C<< <pre> >>として扱われます。  
 プログラムの表示などに使うと便利です。  
   
   
 =item *  
   
 行を > ではじめると、  
 引用文C<< <blockquote> >>が書けます。  
 >の数が多いとインデントが深くなります(3レベルまで)。  
   
     >文章  
     >文章  
     >>さらなる引用  
     >文章  
   
 =back  
   
 =head1 更新履歴  
   
 =over 4  
   
 =item *  
   
 2001年10月20日、Version 1.6.6。  
   
 更新の衝突対策。  
 元ページの簡単なチェックサムを取っておき、  
 更新前にチェックサムを比較する。  
 修正個所はdigestという文字列を検索すれば分かる。  
 本来はMD5などでちゃんとやった方がいいのだけれど。  
   
 衝突時に表示されるメッセージなどは「極悪」さんのページを参考にした。  
   
 =item *  
   
 2001年10月17日、Version 1.6.5。  
   
 プレビュー画面で、更新ボタンを押したときに送信される  
 メッセージの内容をinput要素のtype="hidden"を使って埋め込むのをやめる。  
 代わりに、textarea要素を使う。  
 再プレビュー用にmyspecial_を導入。でもきれいな対策ではない。  
   
 =item *  
   
 2001年8月30日、Version 1.6.4。  
   
 URLでダイレクトにページ名を指定しても、  
 $WikiNameと$BracketName以外のページを作れないようにした。  
 (is_valid_nameとis_editable参照)。  
   
 =item *  
   
 2001年8月30日、Version 1.6.3。  
   
 RecentChangesを編集・再編集不可とした。  
 編集不可ページは@uneditableにページ名を入れる。  
   
 =item *  
   
 2001年2月25日、Version 1.6.1, 1.6.2。  
   
 差分機能のバグ修正。  
 do_previewで'>'が扱えないバグを修正  
 (ユーザからの指摘)。  
   
 =item *  
   
 2001年2月22日、Version 1.6.0。  
 差分機能を実装した。  
   
 =item *  
   
 2001年2月19日、Version 1.5.4。  
 画像ファイルへのリンクは画像にしてみた。  
   
 =item *  
   
 2001年2月19日、Version 1.5.3。  
 RecentChangesの中に削除したページがあるのをやめた。  
 use strict;で引っかかる部分を少し整理(完全ではない)。  
   
 =item *  
   
 2001年2月16日、Version 1.5.2。  
 textareaに表示およびプレビューする前に < や > を &lt; や &gt; に変換した  
 (do_preview, editpage, print_preview_buttons)。  
   
 =item *  
   
 2000年12月27日、Version 1.5.1。  
 プレビュー画面を整理した。  
   
 =item *  
   
 2000年12月22日、Version 1.5.0。  
 全体的にずいぶん書き直した。  
 一覧を別途作成するようにした(do_list)。  
 書き込む前に確認画面を出すようにした(do_preview)。  
 テキストの書き方を編集画面に入れた(do_edit, do_reedit)。  
 WhatsNew→RecentChanges、TopPage→FrontPageに変更した。  
   
 =item *  
   
 2000年12月20日、Version 1.1.0。  
 tieを利用して、dbmopenが使えない場合でも動作するように修正。  
 利用者の1人である「極悪」さんから  
 送っていただいたコードを元にしています。  
   
 =item *  
   
 2000年9月5日、Version 1.0.2。  
  <body color=...> → <body bgcolor=...>  
 利用者からの指摘による。感謝。  
   
 =item *  
   
 2000年8月6日、Version 1.0.1を公開。  
 C MAGAZINE(ソフトバンクパブリッシング)  
 2000年10月号連載記事向け公開版。  
 [[ ]] の最後が「望」のようにシフトJISで  
 0x5Dになる場合の回避を行なった。  
   
 =item *  
   
 2000年8月5日、Version 1.0.0を公開。  
   
 =item *  
   
 2000年7月23日、Version 0.82を公開。  
 編集時のリンクミス。  
 <textarea>の属性変更。  
   
 =item *  
   
 2000年7月22日、Version 0.81を公開。  
 ロゴを組み込む。  
   
 =item *  
   
 2000年7月21日、Version 0.80を公開。  
 PODをCGI中に書き込む。  
   
 =item *  
   
 2000年7月19日、Version 0.70を公開。  
 '''イタリック'''や、--、---、>>、>>>などを実装。  
   
 =item *  
   
 2000年7月18日、Version 0.60を公開。  
 *太字*を''太字''に変更  
   
 =item *  
   
 2000年7月17日、Version 0.50を公開。  
   
 =item *  
   
 2000年7月17日、さらにいろいろ追加する。  
   
 =item *  
   
 2000年7月16日、いろいろ追加。  
   
 =item *  
   
 2000年7月15日、公開。  
   
 =back  
   
 =head1 TODO  
   
     - テキスト表示モード  
     - Charsetを明示。  
     - textarea中の閉じタグ対応  
     - メニューの英語表記付記  
     - プレビューのボタンで、mymsgをinputのvalueに入れているが、改行をそのままvalueにいれてはいけないのではないか。  
     - 「再編集」の機能はブラウザの back で充分ではないか。プレビューはもっとシンプルに。  
     - ページタイトル(Wikiname)が検索にかかるようにする。  
     - InterWiki風の機能「URLを隠しつつ、リンクを張る」  
   
 =head1 作者  
   
     Copyright (C) 2000 by Hiroshi Yuki.  
     結城浩 <hyuki@hyuki.com>  
     http://www.hyuki.com/  
     http://www.hyuki.com/yukiwiki/  
1374    
1375  質問、意見、バグ報告は hyuki@hyuki.com にメールしてください。  sub do_diff {
1376        if (not &is_editable($form{mypage})) {
1377            &do_read;
1378            return;
1379        }
1380        &open_diff;
1381        my $title = $form{mypage};
1382        &print_header($title, -noindex => 1);
1383        $_ = &escape($diffbase{$form{mypage}});
1384        &close_diff;
1385        print qq(<h3>@{[&Resource('Diff:Title',escape=>1)]}</h3>);
1386        print qq(<p>@{[&Resource('Diff:Notice',escape=>1)]}</p>);
1387        print qq(<pre class="diff">);
1388        foreach (split(/\n/, $_)) {
1389            if (/^\+(.*)/) {
1390                print qq(<ins class="added">$1</ins>\n);
1391            } elsif (/^\-(.*)/) {
1392                print qq(<del class="deleted">$1</del>\n);
1393            } elsif (/^\=(.*)/) {
1394                print qq(<span class="same">$1</span>\n);
1395            } else {
1396                print qq|??? $_\n|;
1397            }
1398        }
1399        print qq(</pre>);
1400        &print_footer($title);
1401    }
1402    
1403  =head1 配布条件  sub do_rss {
1404        eval q{use Yuki::RSS};
1405        my $rss = new Yuki::RSS(
1406            version => '1.0',
1407            encoding => &get_charset_name ($kanjicode),
1408        );
1409        my $scheme = 'http';
1410        $scheme = lc $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
1411        my $myuri = "$scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi";
1412        $rss->stylesheet (
1413          href      => $myuri . "?mycmd=TEXT_CSS;mypage=WikiStyle:RSS",
1414          type      => 'text/css',
1415        );
1416        $rss->channel(
1417            title   => &Resource ('RSS:WikiTitle'),
1418            link    => $myuri,
1419            description     => &Resource ('RSS:WikiDescription'),
1420            'dc:language'   => $lang,
1421        );
1422        my $recentchanges = $database{RecentChanges};
1423        my $count = 0;
1424        foreach (split(/\n/, $recentchanges)) {
1425            last if ($count >= 15);
1426            if (/\[\[([^]]+)\]\]/) {
1427              my $title = $1;
1428              $rss->add_item (
1429                title       => &escape($title),
1430                link        => $myuri . '?' . &encode($title),
1431                description => &escape(&get_subjectline($title,delimiter=>'')),
1432                'dc:date'   => &get_info ($title, $info_LastModified),
1433              );
1434              $count++;
1435            }
1436        }
1437        # print RSS information (as XML).
1438        print <<"EOD"
1439    Content-type: application/xml; charset=@{[&get_charset_name ($kanjicode)]}
1440    
1441  YukiWikiは、  @{[$rss->as_string]}
1442  GNU General Public Licenseにて公開します。  EOD
1443    }
1444    
1445  YukiWikiはフリーソフトです。  sub _rfc3339_date ($) {
1446  ご自由にお使いください。    my @time = gmtime (shift);
1447  自分好みのYukiWikiが作れるようにシンプルにしてあります。    sprintf '%04d-%02d-%02dT%02d:%02d:%02d+00:00', $time[5]+1900,$time[4]+1,@time[3,2,1,0];
1448    }
1449    
1450  =head1 謝辞  sub is_exist_page {
1451        my ($name) = @_;
1452        if ($use_exists) {
1453            return exists($database{$name});
1454        } else {
1455            return $database{$name};
1456        }
1457    }
1458    
1459  本家のWikiWikiを作ったCunningham & Cunningham, Inc.に  sub __get_database ($) { $database{ $_[0] } }
1460  感謝します。  sub __set_database ($$) { $database{ $_[0] } = $_[1] }
1461    
1462  YukiWikiを楽しんで使ってくださる  sub do_map {
1463  ネット上の方々に感謝します。      my $page = $form{mypage};
1464        &print_header ($page);
1465        wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
1466        wiki::useragent::add ($ENV{HTTP_USER_AGENT});
1467        my ($r, $c) = get_search_result ($form{mypage});
1468        my $rl = wiki::referer::list_html ($form{mypage});
1469        print "<h2>@{[&Resource('Map:Title',escape=>1)]}</h2>\n<p>@{[&Resource('Map:Description',escape=>1)]}</p>\n";
1470        my %option = (level => 0+&Resource('Map:Depth'), weight_list => {}, not_exist => {},
1471          map_from_here => &Resource('Map:FromHere'),
1472          map_from_here_description => &Resource('Map:FromHereLong'));
1473        &wiki::map::make_list ($page, %option);
1474        print &wiki::map::list_to_html ($page, $option{weight_list}, %option);
1475        if ($c) {
1476          print qq{<h2 id="wikipage-see-also">@{[&Resource('SeeAlso',escape=>1)]}</h2>};
1477          print $r;
1478        }
1479        if ($rl) {
1480          print qq(<div id="wikipage-referer"><h2>@{[&Resource('Referers',escape=>1)]}</h2>\n$rl</div>\n);
1481        }
1482        &print_footer ($page);
1483    }
1484    
1485    my %_Resource;
1486    sub Resource ($;%) {
1487      my ($s, %o) = @_;
1488      unless (defined $_Resource{$s}) {
1489        $_Resource{$_[0]} = &wiki::resource::get ($s, $_Resource{__option});
1490      }
1491      $o{escape} ? &escape ($_Resource{$s}) : $_Resource{$s};
1492    }
1493    
1494    package wiki::referer;
1495    sub add ($$) {
1496      my $page = shift;
1497      my $uri = shift;
1498      unless (ref $uri) {
1499        require URI;
1500        $uri = URI->new ($uri);
1501        ## Some schemes do not have query part.
1502        eval q{ $uri->query (undef) if $uri->query =~ /^[0-9]{6,8}$/ };
1503        $uri->fragment (undef);
1504      }
1505      $uri = $uri->canonical;
1506      return unless $uri;
1507      for my $regex (&get_dont_record) {
1508        return if $uri =~ /$regex/;
1509      }
1510      my %list = get ($page);
1511      $list{ $uri }++;
1512      set ($page, \%list);
1513    }
1514    sub get ($) {
1515      my $page = shift;
1516      split /"/, main::get_info ($page, 'Referer');
1517    }
1518    sub set ($%) {
1519      my $page = shift;
1520      my $list = shift;
1521      main::set_info ($page, Referer => join '"', %$list);
1522    }
1523    
1524    sub get_dont_record () {
1525      map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1526      grep !/^#/,
1527      split /[\x0D\x0A]+/, &main::__get_database ('RefererDontRecord');
1528    }
1529    sub get_site_name () {
1530      my @lines = grep /[^#]/, split /[\x0D\x0A]+/, &main::__get_database('RefererSiteName');
1531      my @item;
1532      for (@lines) {
1533        next if /^#/;
1534        my ($uri, $name) = split /\s+/, $_, 2;
1535        $uri =~ s/\$/\\\$/g;  $uri =~ s/\@/\\\@/g;  $uri =~ s/\//\\\//g;
1536        $name =~ s!([()/\\])!\\$1!g;  $name =~ s/\$([0-9]+)/).__decode (\${$1}).q(/g;
1537        push @item, [$uri, qq(q($name))];
1538      }
1539      @item;
1540    }
1541    
1542    sub list_html ($) {
1543      my $page = shift;
1544      my %list = get ($page);
1545      my $r = '';
1546      my @name = get_site_name;
1547      for my $uri (sort keys %list) {
1548        my $title;
1549        for my $item (@name) {
1550          if ($uri =~ /$item->[0]/) {
1551            $title = $uri;
1552            eval qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e}
1553              or die $@ ;#. qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e};
1554            last;
1555          }
1556        }
1557        my $euri = main::escape ($uri);
1558        if ($title) {
1559          $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri&gt;">@{[main::escape ($title)]}</a></li>\n);
1560        } else {
1561          $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1562        }
1563      }
1564      $r ? qq(<ul>$r</ul>\n) : '';
1565    }
1566    
1567  YukiWikiのロゴをデザインしてくださった橋本礼奈さん  sub __decode ($) {
1568  http://city.hokkai.or.jp/~reina/    my $s = shift;
1569  に感謝します。    $s =~ tr/+/ /;
1570      $s =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/chr hex $1/ge;
1571      main::code_convert (\$s);
1572    }
1573    
1574    package wiki::useragent;
1575    
1576    sub add ($) {
1577      my $s = shift;
1578      return unless length $s;
1579      $s =~ s/([\x00-\x08\x0A-\x1F\x25\x7F-\xFF])/sprintf '%%%02X', unpack 'C', $1/ge;
1580      my %ua;
1581      for (split /\n/, &main::__get_database('WikiUserAgentList')) {
1582        if (/^-\[(\d+)\] (.+)$/) {
1583          my ($t, $n) = ($1, $2);
1584          $n =~ tr/\x0A\x0D//d;
1585          $ua{$n} = $t;
1586        }
1587      }
1588      $ua{$s}++;
1589      my $s = qq(#?SuikaWiki/0.9\n);
1590      for (sort {$ua{$a} <=> $ua{$b}} keys %ua) {
1591        $s .= sprintf qq(-[%d] %s\n), $ua{$_}, $_;
1592      }
1593      &main::__set_database ('WikiUserAgentList' => $s);
1594    }
1595    
1596    package wiki::suikawikiconst;
1597    
1598    sub to_hash ($;$) {
1599      my $page = shift;
1600      my $h = shift || {};
1601      my $val;
1602      for my $line (split /\n/, $page) {
1603        $line =~ tr/\x0A\x0D//d;
1604        if ($val && $line =~ s/^\s+//) {
1605          $h->{$val} .= length $h->{$val} ? "\n" . $line : $line;
1606        } elsif ($line =~ /^(.+):/) {
1607          $val = $1; $h->{$val} = '';
1608        }
1609      }
1610      $h;
1611    }
1612    
1613    package SuikaWiki::Plugin;
1614      our $plugin_directory;  # defined in top of this file.
1615      our %List;
1616    
1617    sub escape ($$) { main::escape ($_[1]) }
1618    sub unescape ($$) { main::unescape ($_[1]) }
1619    sub encode ($$) { main::encode ($_[1]) }
1620    sub decode ($$) { main::decode ($_[1]) }
1621    sub __get_datetime ($) { main::get_now () }
1622    sub resource ($$;%) { shift; &main::Resource (@_) }
1623    sub uri ($$) { $main::uri{$_[1]} }
1624    
1625    sub regist ($@) {
1626        my $pack = shift;
1627        for (@_) {
1628            push @{$List{$_}}, $pack;
1629        }
1630    }
1631    
1632    sub import_plugins () {
1633        opendir PDIR, $plugin_directory;
1634        my @plugin = grep {s/\.pm$//} readdir (PDIR);
1635        closedir PDIR;
1636        for (@plugin) {
1637            eval qq{ use SuikaWiki::Plugin::$_ } unless /[^A-Za-z0-9_]/;
1638            push @{$List{_all}}, qq(SuikaWiki::Plugin::$_);
1639        }
1640    }
1641    
1642    &import_plugins ();
1643    
1644    package wiki::conneg;
1645    
1646    ## BUG: this parser isn't strict.
1647    sub get_accept_lang (;$) {
1648      my $alang = shift || $main::ENV{HTTP_ACCEPT_LANGUAGE};
1649      my %alang = (ja => 0.0002, en => 0.0001);
1650      my $i = 0.1;
1651      for (split /\s*,\s*/, $alang) {
1652        tr/\x09\x0A\x0D\x20//d;
1653        if (/((?:(?!;q=).)+)(?:;q="?([0-9.]+)"?)?/) {
1654          my $l = lc $1; $l =~ tr/\x22\x5C//d;
1655          $alang{$l} = (defined $2 ? $2 : 1.000)*1000;
1656          $alang{$l} += $i unless $alang{$l} == 0;
1657          $i -= 0.001;
1658        }
1659      }
1660      \%alang;
1661    }
1662    
1663    package wiki::resource;
1664    
1665    sub get ($;\%) {
1666      my ($resname, $option) = @_;
1667      $option->{accept_language} ||= &wiki::conneg::get_accept_lang ();
1668      $option->{resource} ||= {};
1669      my $v;
1670      for my $lang (sort {$option->{accept_language}->{$b} <=> $option->{accept_language}->{$a}} grep {$option->{accept_language}->{$_}!=0} keys %{$option->{accept_language}}) {
1671        while (length $lang) {
1672          unless ($option->{accept_language}->{defined $option->{accept_language}->{$lang} ? $lang : '*'} == 0) {
1673            $option->{resource}->{$lang} ||= &wiki::suikawikiconst::to_hash (&main::__get_database('WikiResource:'.$lang));
1674            $v = $option->{resource}->{$lang}->{$resname};
1675            last if defined $v;
1676          }
1677          $lang =~ s/[^+-]*$//; $lang =~ s/[+-]$//;
1678        }
1679        last if defined $v;
1680      }
1681      defined $v ? $v : $resname;
1682    }
1683    
1684    package wiki::map;
1685    
1686    sub make_list ($;%) {
1687      my ($page, %option) = @_;
1688      $option{level} ||= 3;
1689      my %weight;
1690      my $content = &main::__get_database ($page);
1691      $content =~ s{^\#\?([^\x0A\x0D]+)}{
1692        if ($1 =~ /import="([^"]+)"/) {
1693          for (split /\s*,\s*/, $1) {
1694            $weight{$_} += 2;
1695          }
1696        }
1697        $&;
1698      }ges;
1699      ## Bug: this code does not support content type.
1700      $content =~ s{\[\[((?!\#)[^]]+)\](?:>>\d+)?\]}{
1701        $weight{$1}++; $&;
1702      }ge;
1703      delete $weight{$page};        ## Delete myself
1704      for my $page (keys %weight) {
1705        my $w = ($content =~ s/\Q$page\E/$&/g);
1706        $weight{$page} += $w + $weight{$page}; ## Weight of [[name]] is x2.
1707        ($weight{$page} *= 0.1, $option{not_exist}->{$page} = 1) unless &main::is_exist_page ($page);
1708      }
1709      $option{weight_list}->{$page} = \%weight;
1710      if (--$option{level}) {
1711        for my $page (keys %weight) {
1712          &make_list ($page, %option) unless $option{weight_list}->{$page};
1713        }
1714      }
1715      $option{weight_list};
1716    }
1717    
1718    sub list_to_html ($$;%) {
1719      my ($Page, $wlist, %option) = @_;
1720      my $r = '';
1721      $option{outputed}->{$Page} = 1;
1722      for my $page (sort {$wlist->{$Page}->{$b} <=> $wlist->{$Page}->{$a}} keys %{$wlist->{$Page}}) {
1723        $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>);
1724        unless ($option{outputed}->{$page}) {
1725          $r .= &list_to_html ($page, $wlist, %option);
1726        }
1727        $r .= "</li>\n";
1728      }
1729      $r ? qq(<ul class="map">$r</ul>) : '';
1730    }
1731    
1732  tieを使った版の元になるコードを送ってくださった  package main;
1733  「極悪」さんに感謝します。  &main;
1734    exit 0;
1735    
1736  =head1 参照リンク  1;
1737    __END__
1738    =head1 NAME
1739    
1740  =over 4  wiki.cgi - This is YukiWiki, yet another Wiki clone.
1741    walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.
1742    
1743  =item *  =head1 DESCRIPTION
1744    
1745  YukiWikiホームページ  YukiWiki is yet another Wiki clone.
 http://www.hyuki.com/yukiwiki/  
1746    
1747  =item *  YukiWiki can treat Japanese WikiNames (enclosed with [[ and ]]).
1748    YukiWiki provides 'InterWiki' feature, RDF Site Summary (RSS),
1749    and some embedded commands (such as [[#comment]] to add comments).
1750    
1751  本家のWikiWiki  Read F<readme_en.txt> (English) or F<readme_ja.txt> (Japanese) in more detail.
 http://c2.com/cgi/wiki?WikiWikiWeb  
1752    
1753  =item *  =head1 AUTHOR
1754    
1755  本家のWikiWikiの作者(Cunningham & Cunningham, Inc.)  Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/
 http://c2.com/  
1756    
1757  =item *  =head1 LICENSE
1758    
1759  YukiWikiのロゴデザインをしてくださった橋本礼奈さんのページ  Copyright (C) 2000-2002 by Hiroshi Yuki.
 http://city.hokkai.or.jp/~reina/  
1760    
1761  =back  This program is free software; you can redistribute it and/or
1762    modify it under the same terms as Perl itself.
1763    
1764  =cut  =cut

Legend:
Removed from v.1.7  
changed lines
  Added in v.1.42

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24