/[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.4 by wakaba, Mon Feb 4 15:03:23 2002 UTC revision 1.31 by wakaba, Thu Nov 14 10:22:19 2002 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl  #!/usr/bin/perl
 use lib "../lib";  
 use CGI::Carp 'fatalsToBrowser';  
 use Algorithm::Diff qw(traverse_sequences);  
 # use strict;  
2  #  #
3  # yukiwiki.cgi - Yet another WikiWikiWeb clone.  # wiki.cgi - This is YukiWiki, yet another Wiki clone.
4  #  #
5  # Copyright (C) 2000,2001 by Hiroshi Yuki.  # Copyright (C) 2000-2002 by Hiroshi Yuki.
6  # <hyuki@hyuki.com>  # <hyuki@hyuki.com>
7  # http://www.hyuki.com/yukiwiki/  # http://www.hyuki.com/yukiwiki/
8  #  #
9  # This program is free software; you can redistribute it and/or modify  # This program is free software; you can redistribute it and/or
10  # it under the terms of the GNU General Public License as published by  # modify it under the same terms as Perl itself.
 # the Free Software Foundation; either version 2 of the License, or  
 # (at your option) any later version.  
11  #  #
12  # This program is distributed in the hope that it will be useful,  # walwiki.cgi based on yukiwiki.cgi - Yet another WikiWikiWeb clone.
13  # but WITHOUT ANY WARRANTY; without even the implied warranty of  
14  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # Walrus add (debug) start
15  # GNU General Public License for more details.  my $walrus_log;
16  #  my $walrus_debugging = 0;
17  # $Id$  # Walrus add (debug) end
18  ##############################  
19  my $version = "1.6.6";  # Libraries.
20  ##############################  use strict;
21  # 単独テストのときには 1 にする。  use lib qw(./WalWiki/lib);
22  my $testing = 0;  use CGI qw(:standard);
23  ##############################  use CGI::Carp qw(fatalsToBrowser);
24  # 漢字ライブラリ  use Yuki::RSS;
25  my $jcodelib = 'jcode.pl';  use Yuki::DiffText qw(difftext);
26  ##############################  use Yuki::YukiWikiDB;
27  # 保存・表示の漢字コード  use AnyDBM_File;
28  my $kanjicode = 'euc';     # 'sjis' 'euc'  require 'jcode.pl';
29  my $charset = 'euc-jisx0213';  # 'Shift_JIS' 'EUC-JP'  # use Jcode;
30  ##############################  use Fcntl;
31  # dbmopenが使えるなら1、使えないなら0  my $version = '2.0.beta1.2002-05-29';
32  my $dbmopen = 0;  my $walversion;
 ##############################  
 # データベース名(.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;  
 ##############################  
 # アイコンファイル名(カラー版)  
 my $iconfile = '';  
 ##############################  
 # アイコンファイル名(モノクロ版)  
 # my $iconfile = '';  
 ##############################  
 # ページを変更したときにtouchするファイル(''なら何もしない)  
 my $touchfile = 'touch.txt';  
 ##############################  
 # プレビュー用の背景色  
 my $preview_color = '#FFCCCC';  
33  ##############################  ##############################
34  # 全ページのスタイル  #
35  my $style = <<'EOD';  # You MUST modify following '$modifier_...' variables.
36  pre, dl, ul, ol, p, blockquote { line-height:120%; }  #
37  a { text-decoration: none; }  my $modifier_mail = 'w@suika.fam.cx';   # Your mail address, like 'walrus@digit.que.ne.jp'.
38  a:link { color: #0000FF; background-color: #FFFFFF; }  my $modifier_url  = 'http://suika.fam.cx/~wakaba/';     # Your web page, like 'http://digit.que.ne.jp/work/'.
39  a:visited { color: #9900CC; background-color: #FFFFFF; }  my $modifier_name = '和';       # Your name, like 'Makio Tsukamoto'.
40  a:hover { text-decoration: underline; }  # my $modifier_dbtype = 'AnyDBM_File';  # Fast, not available on some server, page size limited.
41  EOD  # my $modifier_dbtype = 'dbmopen';      # Fast, not available on some server, page size limited.
42    my $modifier_dbtype = 'YukiWikiDB';     # Slow, available on all environment.
43    # my $modifier_sendmail = '/usr/sbin/sendmail -t -n'; # Your sendmail.
44    my $modifier_sendmail = ''; # If you don't need mail notification.
45    my $modifier_dir_data = './wikidata'; # Your data directory.
46    my $modifier_rss_title = "SuikaWiki $walversion";
47    my $modifier_rss_link = 'http://suika.fam.cx/~wakaba/-temp/wiki2/wiki'; # Blank is not allowed.
48    my $modifier_rss_description = 'This is SuikaWiki';
49  ##############################  ##############################
50  # テキスト入力部分の大きさ  #
51    # You MAY modify following variables.
52    #
53    my $file_touch = "$modifier_dir_data/touched.txt";
54    my $file_resource = "$modifier_dir_data/resource.txt";
55    my $file_FrontPage = "$modifier_dir_data/frontpage.txt";
56    my $file_conflict = "$modifier_dir_data/conflict.txt";
57    my $file_format = "$modifier_dir_data/format.txt";
58    my $url_cgi = '/~wakaba/-temp/wiki/wiki';       ## MUST be started from '/'
59    my $url_stylesheet = $url_cgi.'?mycmd=TEXT_CSS;mypage=WikiHTMLStyle';
60    my $icontag = '<img src="/icons/folder" alt="*" width="40" height="40" />';
61    my $maxrecent = 50;
62  my $cols = 80;  my $cols = 80;
63  my $rows = 20;  my $rows = 20;
64  ##############################  ##############################
 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 ([[結城浩]]とか[[トラブルシュート]]のようなもの)  
65  #  #
66  # ※シフトJISの2バイト目には ']' が来うるので、  # You MAY, but do NOT NEED modify following variables.
67  # 文字']'を1つ多くとるようにしている。  #
68  #  my $dataname = "$modifier_dir_data/wiki";
69  my $WikiName = '([A-Z][a-z]+([A-Z][a-z]+)+)';  my $infoname = "$modifier_dir_data/info";
70  my $BracketName = '\[\[([^>\s]+?\]?)\]\]';  my $diffname = "$modifier_dir_data/diff";
71    my $editchar = '?';
72  # アイコン部分のタグ  my $subject_delimiter = ' - ';
73  my $IconTag = ''; #<<"EOD";  my $use_autoimg = 1; # automatically convert image URL into <img> tag.
74  #<a href="http://www.hyuki.com/yukiwiki/"><img src="$iconfile"  my $use_exists = 0; # If you can use 'exists' method for your DB.
75  # border="0" width="80" height="80" alt="[YukiWiki]" /></a>  ##############################
76  #EOD  my $InterWikiName = 'InterWikiName';
77    my $RecentChanges = 'RecentChanges';
78  require "$jcodelib";  my $AdminChangePassword = 'AdminChangePassword';
79    my $CompletedSuccessfully = 'CompletedSuccessfully';
80  &init_form($kanjicode);  my $FrontPage = 'HomePage';
81    my $IndexPage = 'IndexPage';
82  if ($testing) {  my $SearchPage = 'SearchPage';
83      %form = (  my $CreatePage = 'CreatePage';
84          # 'mycmd' => 'write',  my $ErrorPage = 'ErrorPage';
85          'mycmd' => 'read',  my $RssPage = 'RssPage';
86          #'mycmd' => 'search',  my $NAME_OF_WikiPageLicense = 'WikiPageLicense';
87          #'mycmd' => 'edit',  my $AdminSpecialPage = 'Admin Special Page'; # must include spaces.
88          'mymsg' => <<"EOD",  ##############################
89  はじめまして。  my $bracket_name = '\[\[(\S+?)\]\]';
90  これからいろいろ書き込みますね。  my $embedded_name = '\[\[(#\S+?)\]\]';
91  LinkPageも見てください。  my %fmt;        ## formatter objects
92  TestPageはどうでしょうか。  ##############################
93  どうぞよろしく。  my $embed_comment = '[[#comment]]';
94  http://www.hyuki.com/  my $embed_rcomment = '[[#rcomment]]';
95  [[結城浩]]  my $embed_comment_Name_Prompt = '名前:';
96  EOD  my $DEFAULT_embed_comment_name = '名無しさん';
97          'mypage' => '<結城浩>',  my $embed_interwiki = '^\[\[#(box|text|password):(\S+)\]\]$';    # Walrus add (5)
98          'myword' => '結',  my %embed_command = (
99          # '3C8C8B8FE98D5F3E' => '',          searched        => '^\[\[#searched:([^\]]+)\]\]$',
100          # 'TestPage' => '',  );
101      );  ##############################
102  }  my $info_LastModified = 'LastModified';
103    my $info_IsFrozen = 'IsFrozen';
104    my $info_AdminPassword = 'AdminPassword';
105    ##############################
106    my $kanjicode = 'euc';
107    my $charset = 'EUC-JP';
108    my $lang = 'ja';
109    my %fixedpage = (
110        $IndexPage => 1,
111        $CreatePage => 1,
112        $ErrorPage => 1,
113        $RssPage => 1,
114        $RecentChanges => 1,
115        $SearchPage => 1,
116        $AdminChangePassword => 1,
117        $CompletedSuccessfully => 1,
118        #$FrontPage => 1,
119    );
120    my %form;
121    my %database;
122    my %infobase;
123    my %diffbase;
124    my %resource;
125    my %interwiki;
126    ##############################
127    my %page_command = (
128        $IndexPage => 'index',
129        $SearchPage => 'searchform',
130        $CreatePage => 'create',
131        $RssPage => 'rss',
132        $AdminChangePassword => 'adminchangepasswordform',
133        #$FrontPage => 'FrontPage',
134    );
135    my %command_do = (
136        read => \&do_read,
137        TEXT_CSS => \&do_output_css,
138        edit => \&do_edit,
139        adminedit => \&do_adminedit,
140        adminchangepasswordform => \&do_adminchangepasswordform,
141        adminchangepassword => \&do_adminchangepassword,
142        write => \&do_write,
143        index => \&do_index,
144        searchform => \&do_searchform,
145        search => \&do_search,
146        create => \&do_create,
147        createresult => \&do_createresult,
148        FrontPage => \&do_FrontPage,
149        comment => \&do_comment,
150        RandomJump  => \&do_random_jump,
151        rss => \&do_rss,
152        diff => \&do_diff,
153        interwikibox => \&do_interwiki_box, # Walrus add (5)
154    );
155    ##############################
156    my @ignore_html_page = ('FrontPage');        # Walrus add (6)
157    my @ignore_html_tags = ('a', 'br', 'img');   # Walrus add (6)
158    my $walversion = '2.0.beta1.wal.1';          # Walrus add (1)
159    ##############################
160    # &test_convert;
161  &main;  &main;
162  exit(0);  exit(0);
163    ##############################
164    
 # メイン  
165  sub main {  sub main {
166      &normalize_form;      &init_resource;
167      if ($dbmopen) {      &open_db;
168          if (!dbmopen(%database, $dbname, 0666)) {      &init_form;
169              &print_error("(dbmopen) $dbname が作れません。");      &init_InterWikiName;
170          }      if ($command_do{$form{mycmd}}) {
171            &{$command_do{$form{mycmd}}};
172      } else {      } else {
173          if (!tie(%database, "YukiWikiDB", $dbname)) {          &do_FrontPage;
             &print_error("(tie error)");  
         }  
     }  
   
     # myspecial対応  
     foreach (keys %form) {  
         if (/^myspecial_(.*)/) {  
             $form{mycmd} = $1;  
             last;  
         }  
     }  
   
     if ($form{mycmd} eq 'read') {  
         &do_read;  
     } elsif ($form{mycmd} eq 'preview') {  
         &do_preview;  
     } elsif ($form{mycmd} eq 'write') {  
         &do_write;  
     } elsif ($form{mycmd} eq 'edit') {  
         &do_edit;  
     } elsif ($form{mycmd} eq 'reedit') {  
         &do_reedit;  
     } elsif ($form{mycmd} eq 'search') {  
         &do_search;  
     } elsif ($form{mycmd} eq 'list') {  
         &do_list;  
     } elsif ($form{mycmd} eq 'diff') {  
         &do_diff;  
     } else {  
         $form{mypage} = $toppage;  
         &do_read;  
     }  
     if ($dbmopen) {  
         dbmclose(%database);  
     } else {  
         untie(%database);  
174      }      }
175        &close_db;
176  }  }
177    
 # ページの表示  
178  sub do_read {  sub do_read {
179      my $page_name = $form{mypage};    my $content = $database{$form{mypage}};
180      my $percent_name = &encode_percent($page_name);    my $lm = &get_info($form{mypage}, $info_LastModified);
181      &print_header($page_name);    wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
182      print qq|<h1>$IconTag<a href="$thisurl?mycmd=search;myword=$percent_name">$page_name</a></h1>\n|;    my ($r, $c) = get_search_result ($form{mypage});
183      &print_toolbar($page_name);    my $rl = wiki::referer::list_html ($form{mypage});
184      print &convert_html(&get_page($page_name));    my @toc;
185      &print_footer;    push @toc, qq(-<a href="#wikipage-see-also">See Also</a>) if $c;
186      push @toc, qq(-<a href="#wikipage-referer">参照元</a>) if $rl;
187        my $cf = 'SuikaWiki/0.9';
188        ## Should be support at least:
189        ## - 'SuikaWiki/0.9' CRLF
190        ## - 'H2H/' ("0.9" / "1.0" / "1.1") CRLF
191        ## - "/*" WSP* 'W3C-CSS/' ("1.0" / "2.0") "*/" CRLF
192        $cf = $1 if $content =~ s#^(?:/\*\s*|[\#<]\?)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+##s;
193        if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
194          &print_header ($form{mypage}, -last_modified => $lm,
195            -content_format => $cf, -noindex => $cf =~ /obsoleted="yes"/);
196          &print_content ($content, content_format => $cf, last_modified => $lm,
197            -toc => \@toc);
198          print &text_to_html (q([[#comment]])) unless $cf =~ /obsoleted="yes"/;
199        } else {
200          &print_header($form{mypage}, -last_modified => $lm);
201          print "<pre>@{[&escape($content)]}</pre>";
202        }
203        if ($c) {
204          print q{<h2 id="wikipage-see-also">See also</h2>};
205          print $r;
206        }
207        if ($rl) {
208          print qq(<div id="wikipage-referer"><h2>参照元</h2>\n$rl</div>\n);
209        }
210      &print_footer($form{mypage}, $lm);
211    }
212    
213    sub do_output_css {
214      my $content = $database{$form{mypage}};
215      if ($content =~ m#^\s*/\*\s*W3C-CSS#) {
216        my $lm = &get_info($form{mypage}, $info_LastModified);
217        print "Content-Type: text/css; charset=$charset\n";
218        print "Last-Modified: $lm\n";
219        print "\n";
220        print $content;
221      } else {
222        print "Status: 406 Unsupported Media Type\n";
223        &print_header('WikiPageIsNotCSS', -noindex => 1);
224        &print_content($database{WikiPageIsNotCSS});
225        &print_footer('WikiPageIsNotCSS');
226      }
227  }  }
228    
 # ページの編集  
229  sub do_edit {  sub do_edit {
230      if (not &is_editable($form{mypage})) {      my ($page) = &unarmor_name(&armor_name($form{mypage}));
231          # 編集不可ページは表示のみ      &print_header($page, -noindex => 1);
232          &do_read;      if (not &is_editable($page)) {
233          return;          &print_message($resource{cantchange});
234        } elsif (&is_frozen($page)) {
235            &print_message($resource{cantchange});
236        } else {
237            &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>0);
238      }      }
239      &editpage(&get_page($form{mypage}));      wiki::referer::add ($form{mypage}, $ENV{HTTP_REFERER});
240  }      my ($r, $c) = get_search_result ($form{mypage});
241        my $rl = wiki::referer::list_html ($form{mypage});
242  # ページの再編集      if ($c) {
243  sub do_reedit {        print q{<h2 id="wikipage-see-also">See also</h2>};
244      if (not &is_editable($form{mypage})) {        print $r;
245          # 編集不可ページは表示のみ      }
246          &do_read;      if ($rl) {
247          print qq(<div id="wikipage-referer"><h2>参照元</h2>\n$rl</div>\n);
248        }
249        &print_footer($page);
250    }
251    
252    sub do_adminedit {
253        my ($page) = &unarmor_name(&armor_name($form{mypage}));
254        &print_header($page, -noindex => 1);
255        if (not &is_editable($page)) {
256            &print_message($resource{cantchange});
257      } else {      } else {
258          &editpage($form{mymsg});          &print_message($resource{passwordneeded});
259            &print_editform($database{$page}, &get_info($page, $info_LastModified), admin=>1);
260      }      }
261        &print_footer($page);
262  }  }
263    
264  sub editpage {  sub do_adminchangepasswordform {
265      my $page_msg = shift;      &print_header($AdminChangePassword, -noindex => 1);
266      my $page_name = $form{mypage};      &print_passwordform;
267      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;  
268  }  }
269    
270  # ページの検索  sub do_adminchangepassword {
271  sub do_search {      if ($form{mynewpassword} ne $form{mynewpassword2}) {
272      if ($form{myword}) {          &print_error($resource{passwordmismatcherror});
273          &print_header('検索結果');      }
274          print qq|<h1>$IconTag$form{myword}の検索結果</h1>\n|;      my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_AdminPassword);
275          &print_toolbar();      if ($validpassword_crypt) {
276          print qq|<ul>\n|;          if (not &valid_password($form{myoldpassword})) {
277          my $count = 0;              &send_mail_to_admin(<<"EOD", "AdminChangePassword");
278          foreach my $page_name (sort keys %database) {    # sortするのは無謀かな  myoldpassword=$form{myoldpassword}
279              if ($database{$page_name} =~ /\Q$form{'myword'}\E/) {  mynewpassword=$form{mynewpassword}
280                  my $encoded = &encode_percent($page_name);  mynewpassword2=$form{mynewpassword2}
281                  print qq|<li><a href="$thisurl?mycmd=read;mypage=$encoded">$page_name</a>\n|;  EOD
282                  $count++;              &print_error($resource{passworderror});
             }  
283          }          }
284          print qq|</ul>\n|;      }
285          if ($count > 0) {      my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
286              print qq|<p><strong>$form{myword}</strong>を含むページは、上に示す<strong>$count</strong> ページです。</p>\n|;      my (@token) = ('0'..'9', 'A'..'Z', 'a'..'z');
287          } else {      my $salt1 = $token[(time | $$) % scalar(@token)];
288              print qq|<p><strong>$form{myword}</strong>を含むページは見つかりません。</p>\n|;      my $salt2 = $token[($sec + $min*60 + $hour*60*60) % scalar(@token)];
289        my $crypted = crypt($form{mynewpassword}, "$salt1$salt2");
290        &set_info($AdminSpecialPage, $info_AdminPassword, $crypted);
291    
292        &print_header($CompletedSuccessfully, -noindex => 1);
293        &print_message($resource{passwordchanged});
294        &print_footer($CompletedSuccessfully);
295    }
296    
297    sub do_index {
298        &print_header($IndexPage);
299        print qq(<ul>);
300        foreach my $page (sort keys %database) {
301            if (&is_editable($page)) {
302                print qq(<li><a href="$url_cgi?@{[&encode($page)]}">@{[&escape($page)]}</a>@{[&escape(&get_subjectline($page))]}</li>);
303                # print qq(<li>@{[&get_info($page, $info_IsFrozen)]}</li>);
304                # print qq(<li>@{[0 + &is_frozen($page)]}</li>);
305          }          }
     } else {  
         &print_header('単語検索');  
         print qq|<h1>$IconTag単語検索</h1>\n|;  
         &print_toolbar();  
306      }      }
307      print <<"EOD";      print qq(</ul>);
308  <p>      &print_footer($IndexPage);
 <form action="$thisurl" method="post">  
 <input type="hidden" name="mycmd" value="search">  
 <input type="text" name="myword" size="20" value="$form{myword}">  
 <input type="submit" value="単語検索">  
 </form>  
 </p>  
 EOD  
     &print_footer;  
309  }  }
310    
311  # ページの一覧  sub do_write {
312  sub do_list {      if (&frozen_reject()) {
313      &print_header('ページ一覧');          return;
     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|;  
314      }      }
     &print_preview_buttons($page_name, $escapedmsg, $form{mydigest});  
     &print_footer;  
 }  
   
 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  
 }  
315    
 # 書き込む  
 sub do_write {  
316      if (not &is_editable($form{mypage})) {      if (not &is_editable($form{mypage})) {
317          # 編集不可ページは表示のみ          &print_header($form{mypage}, -noindex => 1);
318          &do_read;          &print_message($resource{cantchange});
319            &print_footer($form{mypage});
320          return;          return;
321      }      }
322    
323      my $page_name = $form{mypage};      if (&conflict($form{mypage}, $form{mymsg})) {
   
     # digestを使って、更新の衝突チェック  
     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;  
324          return;          return;
325      }      }
326    
327      # diff生成      # Making diff
328      {      {
329          &opendiff;          &open_diff;
330          my @msg1 = split(/\n/, &get_page($page_name));          my @msg1 = split(/\n/, $database{$form{mypage}});
331          my @msg2 = split(/\n/, $form{mymsg});          my @msg2 = split(/\n/, $form{mymsg});
332          $msgrefA = \@msg1;          $diffbase{$form{mypage}} = &difftext(\@msg1, \@msg2);
333          $msgrefB = \@msg2;          &close_diff;
         &diff_check;  
         $diffbase{$form{mypage}} = $diff_text;  
         $diff_text = '';  
         &closediff;  
334      }      }
335    
     &print_header($page_name);  
     &set_page($page_name, $form{mymsg});  
336      if ($form{mymsg}) {      if ($form{mymsg}) {
337          print qq|<h1>$IconTag${page_name}を更新しました</h1>\n|;          $database{$form{mypage}} = $form{mymsg};
338          &print_toolbar($page_name);          &send_mail_to_admin($form{mypage}, "Modify");
339          print &convert_html(&get_page($page_name));          if ($form{mytouch}) {
340      } else {              &set_info($form{mypage}, $info_LastModified, '' . localtime);
341          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 が作れません。");  
342          }          }
343            &set_info($form{mypage}, $info_IsFrozen, 0 + $form{myfrozen});
344            &print_header($CompletedSuccessfully, -noindex => 1, -goto => $url_cgi.'?'.&encode($form{mypage}).($form{__comment_anchor_index}?"#anchor-$form{__comment_anchor_index}":''));
345            &print_message($resource{saved});
346            &print_content("$resource{continuereading} @{[&armor_name($form{mypage})]}");
347            &print_footer($CompletedSuccessfully);
348      } else {      } else {
349          if (!tie(%diffbase, "YukiWikiDB", $diffdbname)) {          &send_mail_to_admin($form{mypage}, "Delete");
350              &print_error("(tie error)");          delete $database{$form{mypage}};
351            delete $infobase{$form{mypage}};
352            if ($form{mytouch}) {
353                &update_recent_changes;
354          }          }
355            &print_header($form{mypage}, -noindex => 1);
356            &print_message($resource{deleted});
357            &print_footer($form{mypage});
358      }      }
359  }  }
360    
361  sub closediff {  sub do_searchform {
362      if ($dbmopen) {      &print_header($SearchPage);
363          dbmclose(%diffbase);      &print_searchform("");
364      } else {      &print_footer($SearchPage);
         untie(%diffbase);  
     }  
 }  
   
 # フォームからの情報を連想配列 %form に入れる  
 # &init_form('euc');  
 sub init_form {  
     my ($charcode) = @_;  
     my $query;  
     if ($ENV{REQUEST_METHOD} =~ /^post$/i) {  
         read(STDIN, $query, $ENV{CONTENT_LENGTH});  
     } else {  
         $query = $ENV{QUERY_STRING};  
     }  
     my @assocarray = split(/[&;]/, $query);  
     foreach my $assoc (@assocarray) {  
         my ($property, $value) = split(/=/, $assoc);  
         $value =~ tr/+/ /;  
         $value =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;  
         &jcode::convert(\$value, $charcode);  
         $form{$property} = $value;  
     }  
365  }  }
366    
367  # エラーページを出力する  sub do_search {
368  sub print_error {      my $word = $form{mymsg};
369      my ($msg) = @_;      &print_header($SearchPage);
370      &print_header('Error');      &print_searchform(&escape($word));
371      print "<h1>$IconTag$msg</h1></body></html>";      print scalar get_search_result ($word, -output_not_found => 1, -match_myself => 1);
372      exit(0);      &print_footer($SearchPage);
373    }
374    
375    sub get_search_result ($;%) {
376      my $word = shift;
377      my %option = @_;
378      my @r;
379      foreach my $page (keys %database) {
380        next if $page eq $RecentChanges || ($page eq $word && !$option{-match_myself});
381        my $content = $database{$page};
382        my $cf = 'SuikaWiki/0.9';
383        $cf = $1 if $content =~ s/^\#\?([^\x0A\x0D]+)//s;
384        next if $cf =~ /obsoleted="yes"/;
385        if (index ($page, $word) > -1) {
386          my $c = $content =~ s/\Q$word\E/$word/g;
387          push @r, [$page, $c+20];
388        } elsif (index ($word, $page) > -1) {
389          my $c = $content =~ s/\Q$word\E/$word/g;
390          push @r, [$page, $c+10];
391        } elsif (my $c = $content =~ s/\Q$word\E/$word/g) {
392          push @r, [$page, $c];
393        }
394      }
395      my $em = sub { my $s = shift; $s =~ s#(\Q$word\E)#<em>$1</em>#g; $s };
396      my $r = join "\n", map {qq(<li>[$_->[1]] <a href ="$url_cgi?@{[&encode($_->[0])]}" class="wiki">@{[&$em(&escape($_->[0]))]}</a> <span class="wikipage-summary">@{[&$em(&escape(&get_subjectline($_->[0])))]}</span></li>)} sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]} @r;
397      $r = qq|<ul class="search-result">$r</ul>| if $r;
398      get_message ($resource{notfound}) if @r == 0 && $option{-output_not_found};
399      wantarray? ($r, scalar @r): $r;
400  }  }
401    
402  sub escape {  sub do_create {
403      my ($line) = shift;      &print_header($CreatePage);
404      $line =~ s|<|&lt;|g;      print <<"EOD";
405      $line =~ s|>|&gt;|g;  <form action="$url_cgi" method="post">
406      $line =~ s|"|&quot;|g;      <input type="hidden" name="mycmd" value="edit">
407      # $line =~ s|\&|&amp;|g;      <strong>$resource{newpagename}</strong><br>
408      return $line;      <input type="text" name="mypage" value="" size="20">
409        <input type="submit" value="$resource{createbutton}"><br>
410    </form>
411    EOD
412        &print_footer($CreatePage);
413  }  }
414    
415  sub inline {  sub do_random_jump {
416      my ($line) = shift;    my @list = keys %database;
417      $line = &escape($line);    my $name = &encode ($list[rand @list]);
418      $line =~ s|'''([^']+?)'''|<strong>$1</strong>|g;    my ($scheme) = 'http';
419      $line =~ s|''([^']+?)''|<em>$1</em>|g;              $scheme = $1 if $main::ENV{SERVER_PROTOCOL} =~ m#([A-Za-z0-9+.%-]+)#;
420      $line =~ s!    print "Location: $scheme://$main::ENV{SERVER_NAME}:$main::ENV{SERVER_PORT}$url_cgi?$name\n";
421                  (    print "\n";
422                      ((mailto|http|https|ftp):[\x21-\x7E]*) # Direct http://...  }
423                          |  
424                      ($WikiName)                         # LocalLinkLikeThis  sub do_FrontPage {
425                          |      open(FILE, $file_FrontPage) or &print_error("($file_FrontPage)");
426                      ($BracketName)                      # [[日本語リンク]]      my $content = join('', <FILE>);
427                  )      &code_convert(\$content, $kanjicode);
428              !      close(FILE);
429                  &make_link($1)      &print_header($FrontPage);
430              !gex;      &print_content($content);
431      return $line;      &print_footer($FrontPage);
432  }  }
433    
434  # ページのタイトルからページの内容を得る  sub print_error {
435  sub get_page {      my ($msg) = @_;
436      my $page_name = shift;      &print_header($ErrorPage, -noindex => 1);
437      return $database{$page_name};      print qq(<p><strong class="error">$msg</strong></p>);
438  }      &print_footer($ErrorPage);
439        exit(0);
 # ページの内容を与える  
 # &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|);  
         }  
     }  
     # ここで本当に更新  
     $database{$whatsnew} = join("\n", splice(@newpages, 0, $maxnew));  
440  }  }
441    
442  # ページのヘッダを出力  sub print_header ($;%) {
443  sub print_header {      my ($page, %option) = @_;
444      my $title = shift;      my $bodyclass = "normal";
445        if (&is_frozen($page) and $form{mycmd} =~ /^(read|write)$/) {
446            $bodyclass = "frozen";
447        }
448        $bodyclass .= " wiki-page-obsoleted" if $option{-content_format} =~ /obsoleted="yes"/;
449        print qq{Refresh: 0; url="$option{-goto}"\n} if $option{-goto};
450        print qq{Last-Modified: $option{-last_modified}\n} if $option{-last_modified};
451        my $cookedpage = &encode($page);
452        my $escapedpage = &escape($page);
453      print <<"EOD";      print <<"EOD";
454  Content-type: text/html  Content-type: text/html; charset=$charset
455    Content-Language: $lang
456  <html><head>  Content-Style-Type: text/css
457  <title>$title</title>  
458  <style type="text/css">  <!--
459  $style  <!DOCTYPE html
460  </style>      PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
461        "http://www.w3.org/TR/html4/loose.dtd"> + RUBY -->
462    <html lang="$lang">
463    <head>
464        <title>$escapedpage</title>
465        <link rel="index" href="$url_cgi?$IndexPage">
466        <link rel="help" href="$url_cgi?WikiHelp">
467        <link rel="copyright" href="$url_cgi?$NAME_OF_WikiPageLicense">
468        <link rel="stylesheet" type="text/css" href="@{[&escape($url_stylesheet)]}">
469        @{[$option{-noindex} ? q(<meta name="ROBOTS" content="NOINDEX">) : '']}
470  </head>  </head>
471  <body>  <body class="$bodyclass">
472    EOD
473      &print_navigate_links ($page);
474      print <<EOD;
475    <h1 class="header">@{[&escape($page)]}</h1>
476  EOD  EOD
477  }  }
478    
479  # ツールバーを出力  sub print_navigate_links (@) {
480  sub print_toolbar {    my ($page) = @_;
481      my $page_name = shift;      my $editable = 0;
482      my $percent_name = &encode_percent($page_name);      my $admineditable = 0;
483      my $editlink = '';      if (&is_frozen($page) and $form{mycmd} =~ /^(read|write)$/) {
484      if ($page_name ne '' and &is_editable($page_name)) {          $editable = 0;
485          $editlink = <<"EOD";          #$admineditable = 1;
486  <a href="$thisurl?mycmd=edit;mypage=$percent_name">編集</a> |      } elsif (&is_editable($page) and $form{mycmd} =~ /^(read|write)$/) {
487  <a href="$thisurl?mycmd=diff;mypage=$percent_name">差分</a> |          #$admineditable = 1;
488  EOD          $editable = 1;
489        } else {
490            $editable = 0;
491      }      }
492      print <<"EOD";      my $cookedpage = &encode($page);
493  <p>    print <<EOH;
494   [  <div class="tools">
495  <a href="$thisurl?mycmd=read;mypage=$toppage">トップ</a> |      @{[ $admineditable
496  <a href="$thisurl?mycmd=list">一覧</a> |          ? qq(<a title="$resource{admineditthispage}" href="$url_cgi?mycmd=adminedit;mypage=$cookedpage">$resource{admineditbutton}</a> | )
497  $editlink          : qq()
498  <a href="$thisurl?mycmd=search">単語検索</a> |      ]}
499  <a href="$thisurl?mycmd=read;mypage=$whatsnew">最終更新</a>      @{[ $editable
500   ]          ? #qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E">$resource{editbutton} <kbd>E</kbd></a> | )
501  </p>          qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=$cookedpage" accesskey="E">編集</a> | )
502  EOD          : qq()
503        ]}
504        @{[ $admineditable
505            ? qq(<a href="$url_cgi?mycmd=diff;mypage=$cookedpage">$resource{diffbutton}</a> | )
506            : qq()
507        ]}
508        <a href="$url_cgi?$CreatePage" class="wiki">新規</a> |
509        <a href="$url_cgi?$IndexPage" class="wiki">$resource{indexbutton}</a> |
510        <a href="$url_cgi?$FrontPage" class="wiki">首頁</a> |
511        <a href="$url_cgi?$SearchPage" class="wiki">$resource{searchbutton}</a> |
512        <a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">どこか</a> |
513        <a href="$url_cgi?$RecentChanges" class="wiki">最新</a>
514    </div>
515    EOH
516    <<EOH;  ## temp
517        <a href="$url_cgi?$CreatePage" class="wiki">$resource{createbutton}</a> |
518        <a href="$url_cgi?$IndexPage" class="wiki">$resource{indexbutton}</a> |
519    <!--    <a href="$url_cgi?$RssPage" class="wiki">$resource{rssbutton}</a> | -->
520        <a href="$url_cgi?$FrontPage" class="wiki">$FrontPage</a> |
521        <a href="$url_cgi?$SearchPage" class="wiki">$resource{searchbutton}</a> |
522        <a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">どこか</a> |
523        <a href="$url_cgi?$RecentChanges" class="wiki">$resource{recentchangesbutton}</a>
524    </div>
525    EOH
526  }  }
527    
 # ページのフッタを出力  
528  sub print_footer {  sub print_footer {
529      print <<"EOD";      my ($page, $lm) = @_;
530  <address>      $walrus_log = ($walrus_debugging) ? &text_to_html("----\n$walrus_log") : '';    # Walrus add (debug)
531  <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>      # Walrus mod (1) start
532  + <a href="$modifierlink">$modifier</a> ${version}.    my $cvslog1 = q$Revision$;
533      my $cvslog2 = q$Date$;
534      print_navigate_links ($page);
535      print <<"EOD";
536    @{[ $lm ? qq(<div id="wikipage-last-modified">Last modified: $lm</div>) : '' ]}
537    <div class="footer">
538    <a href="http://www.hyuki.com/yukiwiki/" title="$version &copy; 2000-2002 by Hiroshi Yuki">YukiWiki</a> <a href="http://digit.que.ne.jp/work/" title="$walversion &copy; 2000-2002 by Makio Tsukamoto">WalWiki</a>
539    <a href="/gate/cvs/wakaba/wiki/" title="CVS Repository of this script ($cvslog2)">SuikaWiki $cvslog1</a>
540    <div class="navigation">
541  [<a href="/" title="このサーバーの首頁">/</a>  [<a href="/" title="このサーバーの首頁">/</a>
542  <a href="/map" title="このサーバーの案内">地図</a>  <a href="/map" title="このサーバーの案内">地図</a>
543  <a href="/search/" title="このサーバーの検索">検索</a>]  <a href="/search/" title="このサーバーの検索">検索</a>]
544  </address>  </div>
545  </body></html>  </div>
546    $walrus_log
547    </body>
548    </html>
549  EOD  EOD
550    #       print <<"EOD";
551    #   <hr>
552    #   <address class="footer">
553    #       <a href="http://www.hyuki.com/yukiwiki/">YukiWiki</a> $version
554    #       &copy; 2000-2002 by <a href="http://www.hyuki.com/">Hiroshi Yuki</a>.<br />
555    #       Modified by <a href="$modifier_url">$modifier_name</a>.
556    #   </address>
557    #   <p class="footer">
558    #       <a href="http://www.hyuki.com/yukiwiki/">$icontag</a>
559    #   </p>
560    #   </body>
561    #   </html>
562    #   EOD
563        # Walrus mod (1) end
564  }  }
565    
566  # URLやページの名前からリンクを作る  sub escape {
567  sub make_link {      my $s = shift;
568      my $name = shift;      $s =~ s|\r\n|\n|g;
569      if ($name =~ /^(http|https|ftp).*?(\.gif|\.png|\.jpeg|\.jpg)?$/) {      $s =~ s|&|&amp;|g;
570          if ($2) {      $s =~ s|<|&lt;|g;
571              return qq|<a href="$name"><img border="0" src="$name" /></a>|;      $s =~ s|>|&gt;|g;
572          } else {      $s =~ s|"|&quot;|g;
573              return qq|<a href="$name">$name</a>|;      return $s;
574          }  }
575      } elsif ($name =~ /^mailto:(.*)/) {  
576          my $address = $1;  sub unescape {
577          return qq|<a href="$name">$address</a>|;      my $s = shift;
578      } elsif ($database{$name}) {      # $s =~ s|\n|\r\n|g;
579          my $percent_name = &encode_percent($name);      $s =~ s|&lt;|<|g;
580          return qq|<a href="$thisurl?mycmd=read;mypage=$percent_name">$name</a>|;      $s =~ s|&gt;|>|g;
581      } else {      $s =~ s|&quot;|"|g;
582          my $percent_name = &encode_percent($name);      $s =~ s|&amp;|&|g;
583          return qq|$name<a href="$thisurl?mycmd=edit;mypage=$percent_name">?</a>|;      return $s;
584      }  }
585  }  
586    sub print_content ($;$) {
587  # %xx の形式にエンコードする      my ($rawcontent, %option) = @_;
588  # これは、      print &text_to_html($rawcontent, toc=>1, %option);
 # http://www.hyuki.com/yukiwiki/yukiwiki.cgi?mycmd=read&mypage=%3C%8C%8B%8F%E9%8D_%3E  
 # という形式のために使われる。  
 # '<結城浩>' → '%3C%8C%8B%8F%E9%8D_%3E'  
 sub encode_percent {  
     my $name = shift;  
     my $encoded = '';  
     foreach my $ch (split(//, $name)) {  
         if ($ch =~ /[A-Za-z0-9_]/) {  
             $encoded .= $ch;  
         } else {  
             $encoded .= '%' . sprintf("%02X", ord($ch));  
         }  
     }  
     return $encoded;  
589  }  }
590    
591  # テキスト本体をHTMLに変換する  sub text_to_html {
592  sub convert_html {      my ($txt, %option) = @_;
     my ($txt) = shift;  
593      my (@txt) = split(/\n/, $txt);      my (@txt) = split(/\n/, $txt);
594        my @toc;
595        my @toc2 = @{$option{-toc}||[]};
596        my $tocnum = 0;
597        my (@saved, @result);
598        unshift(@saved, "</p>");
599        push(@result, "<p>");
600      foreach (@txt) {      foreach (@txt) {
601          chomp;          chomp;
602          if (/^\*\*(.*)/) {          if (/^\*\*\*\*\*([^\x0D\x0A]*)/) {
603              push(@result, splice(@saved), '<h3>' . &inline($1) . '</h3>');              push(@toc, qq(----- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
604          } elsif (/^\*(.*)/) {              push(@result, splice(@saved), qq(<h6 id="i$tocnum">) . &inline($1) . '</h6>');
605              push(@result, splice(@saved), '<h2>' . &inline($1) . '</h2>');              $tocnum++;
606          } elsif (/^----/) {          } elsif (/^\*\*\*\*([^\x0D\x0A]*)/) {
607              push(@result, splice(@saved), '<hr>');              push(@toc, qq(---- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
608          } elsif (/^(-{1,3})(.*)/) {              push(@result, splice(@saved), qq(<h5 id="i$tocnum">) . &inline($1) . '</h5>');
609              &back_push('ul', length($1));              $tocnum++;
610            } elsif (/^\*\*\*([^\x0D\x0A]*)/) {
611                push(@toc, qq(--- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
612                push(@result, splice(@saved), qq(<h4 id="i$tocnum">) . &inline($1) . '</h4>');
613                $tocnum++;
614            } elsif (/^\*\*([^\x0D\x0A]*)/) {
615            # if (/^\*\*(.*)/) {
616            # Walrus mod (6) end
617                push(@toc, qq(-- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
618                push(@result, splice(@saved), qq(<h3><a name="i$tocnum"> </a>) . &inline($1) . '</h3>');
619                $tocnum++;
620            } elsif (/^\*([^\x0D\x0A]*)/) {
621                push(@toc, qq(- <a href="#i$tocnum">@{[&escape($1)||$tocnum]}</a>\n));
622                push(@result, splice(@saved), qq(<h2><a name="i$tocnum"> </a>) . &inline($1) . '</h2>');
623                $tocnum++;
624            } elsif (/^(={1,6})(.*)/) {
625                &back_push('ol', length($1), \@saved, \@result);
626              push(@result, '<li>' . &inline($2) . '</li>');              push(@result, '<li>' . &inline($2) . '</li>');
627            } elsif (/^(-{1,6})(.*)/) {
628              &back_push('ul', length($1), \@saved, \@result);
629              my ($pf, $l) = ('', $2);
630              if (!$main::_EMBEDED && $l =~ s/^\s*\[([0-9]+)\]//) {
631                my $num = 0+$1;
632                $pf = qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
633              }
634              push(@result, '<li>' . $pf . &inline ($l) . '</li>');
635          } elsif (/^:([^:]+):(.*)/) {          } elsif (/^:([^:]+):(.*)/) {
636              &back_push('dl', 1);              &back_push('dl', 1, \@saved, \@result);
637              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');              push(@result, '<dt>' . &inline($1) . '</dt>', '<dd>' . &inline($2) . '</dd>');
638          } elsif (/^(>{1,3})(.*)/) {          } elsif (/^(?!>>\d)(>{1,5})(.*)/) {
639              &back_push('blockquote', length($1));              &back_push('blockquote', length($1), \@saved, \@result);
640                push @result, "<p>";
641              push(@result, &inline($2));              push(@result, &inline($2));
642                unshift @saved, "</p>";
643          } elsif (/^\s*$/) {          } elsif (/^\s*$/) {
644              push(@result, splice(@saved));              push(@result, splice(@saved));
             unshift(@saved, "</p>");  
645              push(@result, "<p>");              push(@result, "<p>");
646                unshift(@saved, "</p>");
647          } elsif (/^(\s+.*)$/) {          } elsif (/^(\s+.*)$/) {
648              &back_push('pre', 1);              &back_push('pre', 1, \@saved, \@result);
649              push(@result, &escape($1)); # Not &inline, but &escape              #push(@result, &escape($1)); # Not &inline, but &escape
650                push(@result, &inline($1));
651    #       } elsif (/^\,(.*)$/) {             # Walrus del (BF)
652            } elsif (/^\,(.*?)[\x0D\x0A]*$/) { # Walrus add (BF)
653                &back_push('table', 1, \@saved, \@result, ' border="1"');
654                #######
655                # This part is taken from Mr. Ohzaki's Perl Memo and Makio Tsukamoto's WalWiki.
656                # XXXXX
657                my $tmp = "$1,";
658                my @value = map {/^"(.*)"$/ ? scalar($_ = $1, s/""/"/g, $_) : $_} ($tmp =~ /("[^"]*(?:""[^"]*)*"|[^,]*),/g);
659                my @align = map {(s/^\s+//) ? ((s/\s+$//) ? ' align="center"' : ' align="right"') : ''} @value;
660                my @colspan = map {($_ eq '==') ? 0 : 1} @value;
661                for (my $i = 0; $i < @value; $i++) {
662                    if ($colspan[$i]) {
663                        while ($i + $colspan[$i] < @value and $value[$i + $colspan[$i]] eq '==') {
664                            $colspan[$i]++;
665                        }
666                        $colspan[$i] = ($colspan[$i] > 1) ? sprintf(' colspan="%d"', $colspan[$i]) : '';
667                        $value[$i] = sprintf('<td%s%s>%s</td>', $align[$i], $colspan[$i], &inline($value[$i]));
668                    } else {
669                        $value[$i] = '';
670                    }
671                }
672                push(@result, join('', '<tr>', @value, '</tr>'));
673                # XXXXX
674                #######
675            } elsif (/^\[(INS|DEL|PRE)\[\s*$/) {
676                push @result, splice (@saved), '<'.lc($1).'>';
677                unshift @saved, "</p>";
678                push @result, "<p>";
679            } elsif (/^\](INS|DEL|PRE)\]\s*$/) {
680                push @result, splice (@saved), '</'.lc($1).'>';
681            } elsif (/^\[([0-9]+)\](.*)$/ && !$main::_EMBEDED) {
682              my $num = 0+$1;
683              push @result, qq(<a name="anchor-$num" id="anchor-$num" class="anchor">[$num]</a>);
684              push @result, &inline ($2);
685          } else {          } else {
686              push(@result, &inline($_));              push(@result, &inline($_));
687          }          }
688      }      }
689      push(@result, splice(@saved));      push(@result, splice(@saved));
690      return join("\n", @result);      
691        my $toc = '';
692        if ($option{toc}) {
693            # Convert @toc (table of contents) to HTML.
694            # This part is taken from Makio Tsukamoto's WalWiki.
695            my (@tocsaved, @tocresult);
696            foreach (@toc,@toc2) {
697                if (/^(-{1,6})(.*)$/) {
698                    &back_push('ul', length($1), \@tocsaved, \@tocresult);
699                    push(@tocresult, '<li>' . $2 . '</li>');
700                }
701            }
702            push(@tocresult, splice(@tocsaved));
703            $toc = join("\n", @tocresult);
704            $toc = $toc ? qq(<div id="wikipage-toc">$toc</div>) : '';
705        }
706        $toc .= join("\n", @result);
707        $toc =~ s#<p>\n</p>##g;
708        $toc =~ s#[\x0D\x0A]+</#</#g;
709        $toc =~ s#<pre>\n#<pre>#g;
710        $toc;
711  }  }
712    
 # &back_push($tag, $count)  
 # $tagのタグを$levelレベルまで詰める。  
713  sub back_push {  sub back_push {
714      my ($tag, $level) = @_;      my ($tag, $level, $savedref, $resultref, $attr) = @_;
715      while (@saved > $level) {      while (@$savedref > $level) {
716          push(@result, shift(@saved));          push(@$resultref, shift(@$savedref));
717      }      }
718      if ($saved[0] ne "</$tag>") {      if ($savedref->[0] ne "</$tag>") {
719          push(@result, splice(@saved));          push(@$resultref, splice(@$savedref));
720      }      }
721      while (@saved < $level) {      while (@$savedref < $level) {
722          unshift(@saved, "</$tag>");          unshift(@$savedref, "</$tag>");
723          push(@result, "<$tag>");          push(@$resultref, "<$tag$attr>");
724      }      }
725  }  }
726    
727  # 編集可能ページか?  sub inline {
728  sub is_editable {      my ($line) = @_;
729      my ($pagename) = @_;      $line = &escape($line);
730      foreach (@uneditable) {      $line =~ s{\[(INS|DEL|SUP|SUB|VAR|CODE|KBD)(?:\(([A-Za-z0-9\x20-]+)\))?\[(.+?)\]\]}{<@{[lc $1]}@{[$2 ? qq( class="$2") : '']}>$3</@{[lc $1]}>}g;
731          if ($pagename eq $_) {      $line =~ s:\[(WEAK)\[(.+?)\]\]:<span class="@{[lc $1]}">$2</span>:g;
732              return 0;      $line =~ s:\[ABBR\[([^]]+)\] \[([^]]+)\]\]:<acronym title="$2">$1</acronym>:g;
733          }      $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;
734        $line =~ s:\[RUBY\[([^]]+)\] \[([^]]+)\]\]:<ruby><rb>$1</rb><rp>(</rp><rt>$2</rt><rp>)</rp></ruby>:g;
735        $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;
736        $line =~ s%\[Q\[([^]]+)\](?: \[&lt;([\x21-\x5A\x5E-\x7E]+)&gt;\])?\]%「<q@{[$2?qq( cite="$2"):'']}>$1</q>」%g;
737        $line =~ s|'''([^']+)'''|<strong>$1</strong>|g;
738        $line =~ s|''([^']+)''|<em>$1</em>|g;
739        $line =~ s{
740          ((?:$bracket_name))       # [[likethis]], [[#comment]], [[Friend:remotelink]]
741          |\[\[([^[]+?)]&gt;&gt;([0-9]+)]   # [[WikiName]>>1]
742          |&gt;&gt;([0-9]+)
743          |&lt;([A-Za-z0-9%]+:(?:(?!&gt;).)+)&gt;
744        }{
745          my ($l, $page,$anchor, $anum, $uri) = ($1, $3,$4, 0+$5, $6);
746          if ($l) {
747            &make_link($l)
748          } elsif (defined $page) {
749            &make_wikilink ($page, anchor => 0+$anchor);
750          } elsif ($anum) {
751            qq(<a href="#anchor-$anum" class="wiki-anchor">&gt;&gt;$anum</a>);
752          } elsif ($uri) {
753            &make_urilink ($uri);
754          }
755        }gex;
756        return $line;
757    }
758    
759    sub make_wikilink ($%) {
760      my ($ename, %option) = @_;
761      my $name = &unescape ($ename);
762      if ($database{$name}) {
763        my $subject = &escape (&get_subjectline ($name, delimiter => ''));
764        if ($option{anchor}) {
765          return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}#anchor-$option{anchor}" class="wiki">$ename&gt;&gt;$option{anchor}</a>);
766        } else {
767          return qq(<a title="$subject" href="$url_cgi?@{[&encode($name)]}" class="wiki">$ename</a>);
768      }      }
769      if (&is_valid_name($pagename)) {    } else {
770          return 1;      return qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=@{[&escape($name)]}" class="wiki not-exist">$ename<span class="mark">$editchar</span></a>);
771      }
772    }
773    
774    sub make_urilink ($;%) {
775      require URI;
776      my $uri = shift;
777      if ($uri =~ s/^IW://) {       ## InterWiki (not URI)
778        $uri = &unescape ($uri);
779        if ($uri =~ /^([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+"):([^\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+|"(?:\\.|[^"\\])+")$/) {
780          my ($site, $name) = ($1, $2);
781          for ($site, $name) {
782            if (s/^"//) { s/"$//; s/\\(.)/$1/g }
783          }
784          if ($interwiki{$site}) {
785            my $uri = &escape ($fmt{interwiki}->replace ($interwiki{$site} => {site => $site, name => $name}));
786            $site = &escape ($site); $name = &escape ($name);
787            qq(&lt;<a href="$uri" class="out-of-wiki interwiki" title="$name ($site); URI: &lt;$uri&gt;">$name</a>&gt;);
788          } else {
789            qq(&lt;未登録の <a href="$url_cgi?InterWikiName" class="wiki">InterWikiName</a>: @{[&escape ($site)]}>);
790          }
791        } else {
792          qq(&lt;不正な <a href="$url_cgi?InterWikiName" class="wiki">InterWikiName</a>: @{[&escape($uri)]}>);
793      }      }
794      return 0;    } elsif ($uri =~ /^urn:/) {   ## URN
795        my $uri2 = &escape (URI->new ('/uri-res/N2L?'.&unescape ($uri), 'http')->canonical);
796        qq(&lt;<a href="$uri2" title="URI: &lt;$uri&gt; (via &lt;$uri2&gt;)" class="out-of-wiki urn">$uri</a>&gt;);
797      } elsif ($uri =~ s/^MAIL://) {        ## mail address (not URI)
798        my $uri2 = &escape (URI->new ('mailto:'.&unescape ($uri))->canonical);
799        qq(&lt;<a href="$uri2" class="out-of-wiki mail">$uri</a>&gt;);
800      } elsif ($uri =~ s/^IMG(?:\([^)]+\))?://) {   ## image (not URI itself)
801        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
802        qq(<img src="$uri2" alt="" title="URI: &lt;$uri2&gt;" class="out-of-wiki">);
803      } else {      ## misc. URI
804        CGI::Carp::warningsToBrowser (0);
805        my $uri2 = &escape (URI->new (&unescape ($uri))->canonical);
806        CGI::Carp::warningsToBrowser (1);
807        qq(&lt;<a href="$uri2" title="URI: &lt;$uri2&gt;" class="out-of-wiki">$uri</a>&gt;);
808      }
809  }  }
810    
811  # Validな名前か?  ## to be obsoleted
812  sub is_valid_name {  sub make_link {
813      my ($pagename) = @_;      my $chunk = shift;
814      if ($pagename =~ /^$WikiName$/) {      # Walrus add (3) start
815          return 1;      $chunk =~ s/^&lt;(.*)&gt;$/$1/;
816      } elsif ($pagename =~ /^$BracketName$/) {      my $name  = $chunk;
817          return 1;      $name = &unarmor_name($name);
818        # Walrus add (3) end
819        if ($chunk =~ /^$embedded_name$/) {
820            return &embedded_to_html($chunk);
821      } else {      } else {
822          return 0;          $chunk = &unarmor_name($chunk);
823            $chunk = &unescape($chunk); # To treat '&' or '>' or '<' correctly.
824            my $cookedchunk = &encode($chunk);
825            if ($database{$chunk}) {
826                my $subject = &escape(&get_subjectline($chunk, delimiter => ''));
827    #           return qq(<a title="$subject" href="$url_cgi?$cookedchunk">$chunk</a>);  # Walrus del (3)
828                return qq(<a title="$subject" href="$url_cgi?$cookedchunk" class="wiki">@{[&escape($name)]}</a>);   # Walrus add (3)
829            } elsif ($page_command{$chunk}) {
830    #           return qq(<a title="$chunk" href="$url_cgi?$cookedchunk">$chunk</a>);    # Walrus del (3)
831                return qq(<a title="$chunk" href="$url_cgi?$cookedchunk" class="wiki">@{[&escape($name)]}</a>);     # Walrus add (3)
832            } else {
833                return qq(<a title="$resource{editthispage}" href="$url_cgi?mycmd=edit;mypage=$cookedchunk" class="wiki">@{[&escape($name)]}<span class="mark">$editchar</span></a>);
834            }
835      }      }
836  }  }
837    
838  # 現在時刻の文字列を得る  sub print_message {
839  sub get_current_datestr {      my ($msg) = @_;
840      my (@wdays) = ( "日", "月", "火", "水", "木", "金", "土" );      print qq(<p><strong>$msg</strong></p>);
841      my ($sec, $min, $hour, $mday, $mon, $year, $wday) = localtime(time);  }
842      return sprintf("%4d-%02d-%02d (%s) %02d:%02d:%02d",  
843          $year + 1900, $mon + 1, $mday, $wdays[$wday], $hour, $min, $sec);  sub get_message {
844  }      my ($msg) = @_;
845        qq(<p><strong>$msg</strong></p>);
846  # URL?SomePageや、  }
847  # URL?[[結城浩]]の形式だった場合、(not yet)  
848  # 強制的にmycmdをreadにして$formの内容を設定する。  sub init_form {
849  sub normalize_form {      if (param()) {
850      foreach my $key (keys %form) {          foreach my $var (param()) {
851          if ($key =~ /^$WikiName$/) {              $form{$var} = param($var);
852              $form{mycmd} = 'read';        }
853              $form{mypage} = $1;      }
854              last;      if ($main::ENV{QUERY_STRING} && $main::ENV{QUERY_STRING} !~ /[&;]/) {
855          } elsif ($key =~ /^$BracketName$/) {        my $query = &decode($main::ENV{QUERY_STRING});
856              $form{mycmd} = 'read';        if ($page_command{$query}) {
857              $form{mypage} = $1;          $form{mycmd} = $page_command{$query};
858              last;          $form{mypage} = $query;
859          } else {
860            $form{mypage} = $query;
861            $form{mycmd} = $database{$form{mypage}} ? 'read' : 'edit';
862          }
863        }
864        $form{mypage} ||= 'HomePage';
865    
866        # mypreview_edit        -> do_edit, with preview.
867        # mypreview_adminedit   -> do_adminedit, with preview.
868        # mypreview_write       -> do_write, without preview.
869        foreach (keys %form) {
870            if (/^mypreview_(.*)$/) {
871                $form{mycmd} = $1;
872                $form{mypreview} = 1;
873            }
874        }
875    
876        #
877        # $form{mycmd} is frozen here.
878        #
879    
880        $form{mymsg} = &code_convert(\$form{mymsg}, $kanjicode);
881        $form{myname} = &code_convert(\$form{myname}, $kanjicode);
882    }
883    
884    sub update_recent_changes {
885        my $update = "- @{[&get_now]} [[@{[&escape($form{mypage})]}]] @{[&get_subjectline($form{mypage})]}";
886        my @oldupdates = split(/\r?\n/, $database{$RecentChanges});
887        my @updates;
888        foreach (@oldupdates) {
889            /^\- \d\d\d\d\-\d\d\-\d\d \([^)]+\) \d\d:\d\d \[\[(\S+?)\]\]/;
890            my $name = $1;
891            if ($name ne $form{mypage}) {
892                push @updates, $_;
893          }          }
894      }      }
895        if (&is_exist_page($form{mypage})) {
896          unshift @updates, $update;
897        }
898        splice(@updates, $maxrecent + 1);
899        $database{$RecentChanges} = join("\n", @updates);
900        if ($file_touch) {
901            open(FILE, "> $file_touch");
902            print FILE localtime() . "\n";
903            close(FILE);
904        }
905  }  }
906    
907  # 変換テストを行なうときのサンプル  sub get_subjectline {
908  sub print_sample {      my ($page, %option) = @_;
909      my $txt = &convert_html(<<"EOD");      if (not &is_editable($page)) {
910  *大見出し1          return "";
911  **小見出し1-1      } else {
912  -項目1          # Delimiter check.
913  -項目2          my $delim = $subject_delimiter;
914  -項目3          if (defined($option{delimiter})) {
915  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1              $delim = $option{delimiter};
916  段落1段落1段落1段落1段落1段落''強調''1段落1段落1段落1段落1段落1          }
 段落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  
 **小見出し1-2  
 :用語1:いろいろ書いた解説文1と''強調単語''  
 段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1  
 段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1  
 段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1  
 :用語2:いろいろ書いた解説文2  
 :用語3:いろいろ書いた解説文3  
 ----  
 *大見出し2  
 **小見出し2-1  
 http://www.hyuki.com/  
 **小見出し2-2  
917    
918  [[結城浩]]          # Get the subject of the page.
919            my $subject = $database{$page};
920            $subject =~ s#^(?:\#\?)?SuikaWiki/0.9[^\x0D\x0A]*[\x0D\x0A]+##s;
921            $subject =~ s/\r?\n.*//s;
922            return "$delim$subject".$option{tail};
923        }
924    }
925    
926  段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1段落1  sub send_mail_to_admin {
927  段落1段落1段落1段落'''強調'''1段落1段落1段落1段落1段落1段落1段落1      my ($page, $mode) = @_;
928  段落1段落1段落1段落'''''強い強調'''''1段落1段落1段落1段落1段落1段落1段落1段落1      return unless $modifier_sendmail;
929  >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2      my $message = <<"EOD";
930  >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2  To: $modifier_mail
931  >段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2段落2  From: $modifier_mail
932    Subject: [Wiki]
933  レベル0レベル0レベル0レベル0レベル0レベル0  MIME-Version: 1.0
934    Content-Type: text/plain; charset=ISO-2022-JP
935  >レベル1  Content-Transfer-Encoding: 7bit
936  >レベル1  
937  >レベル1  --------
938  >>レベル2  MODE = $mode
939  >>レベル2  REMOTE_ADDR = $ENV{REMOTE_ADDR}
940  >>レベル2  REMOTE_HOST = $ENV{REMOTE_HOST}
941  >>>レベル3  --------
942  -はろ1  $page
943  --はろ2  --------
944  ろろろろ2  $database{$page}
945  ---はろ3  --------
 --はろ2  
 ---はろ3  
 --はろ2  
 ---はろ3  
 >>>レベル3  
 >>>レベル3  
 >>>レベル3  
946  EOD  EOD
947      print $txt;      &code_convert(\$message, 'jis');
948      exit;      open(MAIL, "| $modifier_sendmail");
949        print MAIL $message;
950        close(MAIL);
951  }  }
952    
953  sub diff_check {  sub open_db {
954      traverse_sequences(      if ($modifier_dbtype eq 'dbmopen') {
955              $msgrefA, $msgrefB,          dbmopen(%database, $dataname, 0666) or &print_error("(dbmopen) $dataname");
956              {          dbmopen(%infobase, $infoname, 0666) or &print_error("(dbmopen) $infoname");
957                  MATCH => \&df_match,      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
958                  DISCARD_A => \&df_delete,          tie(%database, "AnyDBM_File", $dataname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $dataname");
959                  DISCARD_B => \&df_add,          tie(%infobase, "AnyDBM_File", $infoname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $infoname");
960              }      } else {
961      );          tie(%database, "Yuki::YukiWikiDB", $dataname) or &print_error("(tie Yuki::YukiWikiDB) $dataname");
962      &diff_flush;          tie(%infobase, "Yuki::YukiWikiDB", $infoname) or &print_error("(tie Yuki::YukiWikiDB) $infoname");
963        }
964  }  }
965    
966  sub diff_flush {  sub close_db {
967      $diff_text .= join('', map { "-$_\n" } splice(@diff_deleted));      if ($modifier_dbtype eq 'dbmopen') {
968      $diff_text .= join('', map { "+$_\n" } splice(@diff_added));          dbmclose(%database);
969            dbmclose(%infobase);
970        } elsif ($modifier_dbtype eq 'AnyDBM_File') {
971            untie(%database);
972            untie(%infobase);
973        } else {
974            untie(%database);
975            untie(%infobase);
976        }
977  }  }
978    
979  sub df_match {  sub open_diff {
980      my ($a, $b) = @_;      if ($modifier_dbtype eq 'dbmopen') {
981      &diff_flush;          dbmopen(%diffbase, $diffname, 0666) or &print_error("(dbmopen) $diffname");
982      $diff_text .= "=$msgrefA->[$a]\n";      } elsif ($modifier_dbtype eq 'AnyDBM_File') {
983            tie(%diffbase, "AnyDBM_File", $diffname, O_RDWR|O_CREAT, 0666) or &print_error("(tie AnyDBM_File) $diffname");
984        } else {
985            tie(%diffbase, "Yuki::YukiWikiDB", $diffname) or &print_error("(tie Yuki::YukiWikiDB) $diffname");
986        }
987  }  }
988    
989  sub df_delete {  sub close_diff {
990      my ($a, $b) = @_;      if ($modifier_dbtype eq 'dbmopen') {
991      push(@diff_deleted, $msgrefA->[$a]);          dbmclose(%diffbase);
992        } elsif ($modifier_dbtype eq 'AnyDBM_File') {
993            untie(%diffbase);
994        } else {
995            untie(%diffbase);
996        }
997  }  }
998    
999  sub df_add {  sub print_searchform {
1000      my ($a, $b) = @_;      my ($word) = @_;
1001      push(@diff_added, $msgrefB->[$b]);      print <<"EOD";
1002    <form action="$url_cgi" method="get">
1003        <input type="hidden" name="mycmd" value="read">
1004        <input type="text" name="mypage" value="$word" size="20">
1005        <input type="submit" value="$resource{searchbutton}">
1006    </form>
1007    EOD
1008  }  }
1009    
1010  sub calc_message_digest {   # You have to use MD5...  sub print_editform {
1011      my $text = shift;      my ($mymsg, $lastmodified, %mode) = @_;
1012      my @text = split(//, $text);      my $frozen = &is_frozen($form{mypage});
1013      my $len = length($text);  
1014      my $checksum = 0;      if ($form{mypreview}) {
1015      foreach (@text) {          if ($form{mymsg}) {
1016          $checksum += ord($_);              unless ($mode{conflict}) {
1017          $checksum = ($checksum * 2) % 65536 + (($checksum & 32768) ? 1 : 0); # 16bit rotate                  print qq(<h3>$resource{previewtitle}</h3>\n);
1018                    print qq($resource{previewnotice}\n);
1019                    print qq(<div class="preview">\n);
1020                    &print_content($form{mymsg});
1021                    print qq(</div>\n);
1022                }
1023            } else {
1024                print qq($resource{previewempty});
1025            }
1026            $mymsg = &escape($form{mymsg});
1027        } else {
1028            $mymsg = &escape($mymsg || $database{NewPageTemplate});
1029      }      }
     return "$len:$checksum";  
 }  
1030    
1031  # Definition of YukiWikiDB      my $edit = $mode{admin} ? 'adminedit' : 'edit';
1032  package YukiWikiDB;      my $escapedmypage = &escape($form{mypage});
1033        my $escapedmypassword = &escape($form{mypassword});
1034    
1035  my $debug = 1;      print <<"EOD";
1036    <form action="$url_cgi" method="post">
1037  # Constructor  <h2>$escapedmypageの編集</h2>
1038  sub new {      @{[ $mode{admin} ? qq($resource{frozenpassword} <input type="password" name="mypassword" value="$escapedmypassword" size="10"><br>) : "" ]}
1039      return shift->TIEHASH(@_);      <input type="hidden" name="myLastModified" value="$lastmodified">
1040        <input type="hidden" name="mypage" value="$escapedmypage">
1041        <textarea cols="$cols" rows="$rows" name="mymsg" tabindex="1">$mymsg</textarea><br>
1042    @{[
1043        $mode{admin} ?
1044        qq(
1045        <input type="radio" name="myfrozen" value="1" @{[$frozen ? qq(checked="checked") : ""]}>$resource{frozenbutton}
1046        <input type="radio" name="myfrozen" value="0" @{[$frozen ? "" : qq(checked="checked")]}>$resource{notfrozenbutton}<br>)
1047        : ""
1048    ]}
1049    @{[
1050        $mode{conflict} ? "" :
1051        qq(
1052            <input type="checkbox" name="mytouch" value="on" checked="checked">$resource{touch}<br>
1053            <input type="submit" name="mypreview_$edit" value="$resource{previewbutton}">
1054            <input type="submit" name="mypreview_write" value="$resource{savebutton}" accesskey="S"><kbd>S</kbd>
1055            [@{[do {my $n = 0;
1056                   $mymsg =~ s/(?:-+\s)?\[([0-9]+)\]/$n = $1 if $1 > $n; $&/mge;
1057                   ++$n}]}]<br>
1058        )
1059    ]}
1060    </form>
1061    EOD
1062        unless ($mode{conflict}) {
1063            # Show the format rule.
1064            my $help = $database{'WikiEditHelp'};
1065            $help =~ s!^\#\?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.\x0D\x0A][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1066            print &text_to_html ($help, toc => 0);
1067        #    open(FILE, $file_format) or &print_error("($file_format)");
1068        #    my $content = join('', <FILE>);
1069        #    &code_convert(\$content, $kanjicode);
1070        #    close(FILE);
1071        #    print &text_to_html($content, toc=>0);
1072        }
1073  }  }
1074    
1075  # tying  sub print_passwordform {
1076  sub TIEHASH {          print <<"EOD";
1077      my ($class, $dbname) = @_;  <form action="$url_cgi" method="post">
1078      my $self = {      <input type="hidden" name="mycmd" value="adminchangepassword">
1079          dir => $dbname,      $resource{oldpassword} <input type="password" name="myoldpassword" size="10"><br>
1080          keys => [],      $resource{newpassword} <input type="password" name="mynewpassword" size="10"><br>
1081      };      $resource{newpassword2} <input type="password" name="mynewpassword2" size="10"><br>
1082      if (not -d $self->{dir}) {      <input type="submit" value="$resource{changepasswordbutton}"><br>
1083          if (!mkdir($self->{dir}, 0777)) {  </form>
1084              print "mkdir(" . $self->{dir} . ") fail\n" if ($debug);  EOD
             return undef;  
         }  
     }  
     return bless($self, $class);  
1085  }  }
1086    
1087  # Store  sub is_editable {
1088  sub STORE {      my ($page) = @_;
1089      my ($self, $key, $val) = @_;      if ($fixedpage{$page} || $page =~ /\s/ || $page =~ /^\#/) {
1090      my $file = &make_filename($self, $key);          return 0;
     if (open(FILE,"> $file")) {  
         binmode(FILE);  
         print FILE $val;  
         close(FILE);  
         return $self->{$key} = $val;  
1091      } else {      } else {
1092          print "$file create error.";          return 1;
1093      }      }
1094  }  }
1095    
1096  # Fetch  # armor_name:
1097  sub FETCH {  #   WikiName -> WikiName
1098      my ($self, $key) = @_;  #   not_wiki_name -> [[not_wiki_name]]
1099      my $file = &make_filename($self, $key);  sub armor_name { qq([[$_[0]]]) }
1100      if (open(FILE, $file)) {  
1101          local $/;  # unarmor_name:
1102          $self->{$key} = <FILE>;  #   [[bracket_name]] -> bracket_name
1103          close(FILE);  #   WikiName -> WikiName
1104    sub unarmor_name {
1105        my ($name) = @_;
1106        if ($name =~ /^$bracket_name$/) {
1107            return $1;
1108        } else {
1109            return $name;
1110      }      }
     return $self->{$key};  
1111  }  }
1112    
1113  # Exists  sub decode {
1114  sub EXISTS {      my ($s) = @_;
1115      my ($self, $key) = @_;      $s =~ tr/+/ /;
1116      my $file = &make_filename($self, $key);      $s =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/pack("C", hex($1))/eg;
1117      return -e($file);      return $s;
1118  }  }
1119    
1120  # Delete  sub encode {
1121  sub DELETE {      my ($s) = @_;
1122      my ($self, $key) = @_;      my $encoded = '';
1123      my $file = &make_filename($self, $key);      foreach my $ch (split(//, $s)) {
1124      unlink $file;          if ($ch =~ /[A-Za-z0-9_]/) {
1125      return delete $self->{$key};              $encoded .= $ch;
1126            } else {
1127                $encoded .= '%' . sprintf("%02X", ord($ch));
1128            }
1129        }
1130        return $encoded;
1131  }  }
1132    
1133  sub FIRSTKEY {  sub init_resource {
1134      my ($self) = @_;      open(FILE, $file_resource) or &print_error("(resource)");
1135      opendir(DIR, $self->{dir}) or die $self->{dir};      while (<FILE>) {
1136      @{$self->{keys}} = grep /\.txt$/, readdir(DIR);          chomp;
1137      foreach my $name (@{$self->{keys}}) {          next if /^#/;
1138          $name =~ s/\.txt$//;          my ($key, $value) = split(/=/, $_, 2);
1139          $name =~ s/[0-9A-F][0-9A-F]/pack("C", hex($&))/eg;          $resource{$key} = &code_convert(\$value, $kanjicode);
1140      }      }
1141      return shift @{$self->{keys}};      close(FILE);
1142  }  }
1143    
1144  sub NEXTKEY {  sub conflict {
1145      my ($self) = @_;      my ($page, $rawmsg) = @_;
1146      return shift @{$self->{keys}};      if ($form{myLastModified} eq &get_info($page, $info_LastModified)) {
1147            return 0;
1148        }
1149        open(FILE, $file_conflict) or &print_error("(conflict)");
1150        my $content = join('', <FILE>);
1151        &code_convert(\$content, $kanjicode);
1152        close(FILE);
1153        &print_header($page, -noindex => 1);
1154        &print_content($content);
1155        &print_editform($rawmsg, $form{myLastModified}, frozen=>0, conflict=>1);
1156        &print_footer($page);
1157        return 1;
1158    }
1159    
1160    sub get_now {
1161        my (@week) = qw(Sun Mon Tue Wed Thu Fri Sat);
1162        my (@week) = qw(日 月 火 水 木 金 土);
1163        my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
1164        $year += 1900;
1165        $mon++;
1166        $mon = "0$mon" if $mon < 10;
1167        $day = "0$day" if $day < 10;
1168        $hour = "0$hour" if $hour < 10;
1169        $min = "0$min" if $min < 10;
1170        #$sec = "0$sec" if $sec < 10;
1171        $weekday = $week[$weekday];
1172        return "$year-$mon-$day ($weekday) $hour:$min";
1173    }
1174    
1175    sub init_InterWikiName {
1176      my @content = split /\n/, $database{$InterWikiName};
1177      for (@content) {
1178        if (/^([^#]\S*)\s+(\S[^\x0A\x0D]+)/) {
1179          $interwiki{$1} = $2;
1180        }
1181      }
1182      require Message::Util::Formatter;
1183      $fmt{interwiki} = Message::Util::Formatter->new;
1184      $fmt{interwiki}->{encoded} = sub {
1185        my ($o, $p) = @_;
1186        if ($o->{except}) {
1187          $o->{except} =~ tr/\x00-\x20<>\x23%\x22{|}\x5C^[]`\x7F-\xFF//d;
1188        }
1189        my $s = &code_convert (\$p->{name}, $o->{charset} || 'iso-2022-7bit');
1190        $s =~ s/([^$o->{except}A-Za-z0-9_-])/sprintf '%02X', unpack 'C', $1/ge;
1191        $s;
1192      };
1193      $fmt{interwiki}->{ykwk} = sub {       ## YukiWiki1
1194        my ($o, $p) = @_;
1195        my $s = $p->{name};
1196        $s = qq([[$s]]) if $s !~ /^[A-Z][a-z]+(?:[A-Z][a-z]+)+$/;
1197        &encode (&code_convert (\$p->{name}, $o->{charset} || 'shift_jis'));
1198      };
1199    }
1200    
1201    
1202    sub get_info {
1203        my ($page, $key) = @_;
1204        my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1205        return $info{$key};
1206    }
1207    
1208    sub set_info {
1209        my ($page, $key, $value) = @_;
1210        my %info = map { split(/=/, $_, 2) } split(/\n/, $infobase{$page});
1211        $info{$key} = $value;
1212        my $s = '';
1213        for (keys %info) {
1214            $s .= "$_=$info{$_}\n";
1215        }
1216        $infobase{$page} = $s;
1217    }
1218    
1219    sub frozen_reject {
1220        my ($isfrozen) = &get_info($form{mypage}, $info_IsFrozen);
1221        my ($willbefrozen) = $form{myfrozen};
1222        if (not $isfrozen and not $willbefrozen) {
1223            # You need no check.
1224            return 0;
1225        } elsif (valid_password($form{mypassword})) {
1226            # You are admin.
1227            return 0;
1228        } else {
1229            &print_error($resource{passworderror});
1230            return 1;
1231        }
1232  }  }
1233    
1234  sub make_filename {  sub valid_password {
1235      my ($self, $key) = @_;      my ($givenpassword) = @_;
1236      my $enkey = '';      my ($validpassword_crypt) = &get_info($AdminSpecialPage, $info_AdminPassword);
1237      foreach my $ch (split(//, $key)) {      if (crypt($givenpassword, $validpassword_crypt) eq $validpassword_crypt) {
1238          $enkey .= sprintf("%02X", ord($ch));          return 1;
1239        } else {
1240            return 0;
1241      }      }
     return $self->{dir} . "/$enkey.txt";  
1242  }  }
 __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> >>になります。  
   
 =item *  
   
 行をマイナス-ではじめると、  
 箇条書きC<< <ul> >>になります。  
 マイナスの数が増えるとレベルが下がります(3レベルまで)  
   
     -項目1  
     --項目1-1  
     --項目1-2  
     -項目2  
     -項目3  
     --項目3-1  
     ---項目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のページ名になります。  
 大かっこの中にはスペースを含めてはいけません。  
 日本語も使えます。  
1243    
1244  =back  sub is_frozen {
1245        my ($page) = @_;
1246  =item *      if (&get_info($page, $info_IsFrozen)) {
1247            return 1;
1248  行頭がスペースやタブで始まっていると、      } else {
1249  それは整形済みの段落C<< <pre> >>として扱われます。          return 0;
1250  プログラムの表示などに使うと便利です。      }
1251    }
   
 =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  
1252    
1253  =head1 TODO  sub do_comment {
1254        my ($content) = $database{$form{mypage}};
1255        my $default_name;   ## this code does not strict.
1256        $default_name = $1 if $content =~ /default-name="([^"]+)"/;
1257        my $datestr = '[WEAK['.&get_now.']]';
1258        my $namestr = $form{myname} || $default_name || $DEFAULT_embed_comment_name;
1259        ($namestr = '', $datestr = '') if $form{myname} eq 'nodate';
1260        if ($namestr =~ /^(?:>>)?[0-9]/) {
1261          $namestr = qq( ''$namestr'': );
1262        } elsif (length $namestr) {
1263          $namestr = qq( ''[[$namestr]]'': );
1264        }
1265        my $anchor = 0;
1266        $content =~ s/(?:-+\s)?\[([0-9]+)\]/$anchor = $1 if $1 > $anchor; $&/mge;
1267        $anchor++;
1268        my $i = 1;  my $o = 0;
1269        $content =~ s{(\Q$embed_comment\E|\Q$embed_rcomment\E)}{
1270          my $embed = $1;
1271          if ($i == $form{comment_index}) {
1272            if ($embed eq $embed_comment) {
1273              $embed = "- [$anchor] $datestr$namestr$form{mymsg}\n$embed";  $o = 1;
1274            } else {
1275              $embed .= "\n- [$anchor] $datestr$namestr$form{mymsg}";  $o = 1;
1276            }
1277          }
1278          $i++; $embed;
1279        }ge;
1280        unless ($o) {
1281          $content = "#?SuikaWiki/0.9\n\n" unless $content;
1282          $content .= "\n" unless $content =~ /\n$/s;
1283          $content .= "- [$anchor] $datestr$namestr$form{mymsg}\n";
1284        }
1285        $form{__comment_anchor_index} = $anchor;
1286        if ($form{mymsg} || $form{myname}) {
1287            $form{mymsg} = $content;
1288            $form{mytouch} = 'on';
1289            &do_write;
1290        } else {
1291            $form{mycmd} = 'read';
1292            &do_read;
1293        }
1294    }
1295    
1296      - テキスト表示モード  my $CommentIndex = 0;
1297      - Charsetを明示。  sub embedded_to_html {
1298      - textarea中の閉じタグ対応      my ($embedded) = @_;
1299      - メニューの英語表記付記      if ($embedded eq $embed_comment or $embedded eq $embed_rcomment) {
1300      - プレビューのボタンで、mymsgをinputのvalueに入れているが、改行をそのままvalueにいれてはいけないのではないか。        unless ($main::_EMBEDED) {
1301      - 「再編集」の機能はブラウザの back で充分ではないか。プレビューはもっとシンプルに。          my $lastmodified = &get_info($form{mypage}, $info_LastModified);
1302      - ページタイトル(Wikiname)が検索にかかるようにする。          return <<"EOD";
1303      - InterWiki風の機能「URLを隠しつつ、リンクを張る」  <form action="$url_cgi" method="post" id="x-comment-@{[++$CommentIndex]}" class="comment"><p>
1304        <input type="hidden" name="mycmd" value="comment">
1305        <input type="hidden" name="mypage" value="$form{mypage}">
1306        <input type="hidden" name="myLastModified" value="$lastmodified">
1307        <input type="hidden" name="mytouch" value="on">
1308        <input type="hidden" name="comment_index" value="$CommentIndex">
1309        $embed_comment_Name_Prompt
1310        <input type="text" name="myname" value="" size="10" class="comment-name">
1311        <input type="text" name="mymsg" value="" size="60" class="comment-msg">
1312        <input type="submit" value="$resource{commentbutton}" class="comment-submit">
1313    </p></form>
1314    EOD
1315         } else {
1316            return <<"EOD";
1317    <del><form action="$url_cgi" method="get">
1318        <input type="hidden" name="mycmd" value="read">
1319        <input type="hidden" name="mypage" value="$form{mypage}">
1320        $embed_comment_Name_Prompt
1321        <input type="text" name="myname" value="" size="10" disabled="disabled">
1322        <input type="text" name="mymsg" value="" size="60" disabled="disabled">
1323        <input type="submit" value="$resource{commentbutton}" disabled="disabled">
1324    </form></del>
1325    EOD
1326        }
1327      } elsif ($embedded =~ /$embed_command{searched}/) {
1328        return get_search_result ($1, -match_myself => 1);
1329        # Walrus add (5) start
1330        } elsif ($embedded =~ /$embed_interwiki/ and my $remoteurl = $interwiki{$2}) {
1331            $_ = &make_interwiki_box($1, $2);
1332            return ($_) ? $_ : $embedded;
1333        # Walrus add (5) end
1334      } elsif ($embedded =~ /^\[\[\#embed:(.+)\]\]$/) {
1335        my ($name, $r) = ($1, '');
1336        if ($main::_EMBEDED != 1) {
1337          my ($content, $cf) = ($database{$name}, 'SuikaWiki/0.9');
1338          $cf = $1 if $content =~ s!^(?:[\#<]\?|/\*\s*)?([A-Z][A-Za-z0-9-]+/[0-9.]+(?:[^0-9.][^\x0D\x0A]*)?)[\x0D\x0A]+!!s;
1339          if ($cf =~ m!^(?:\#\?)?SuikaWiki/0.9(?:$|\s)!) {
1340            $main::_EMBEDED = 1;
1341            $r = &text_to_html ($content, content_format => $cf);
1342            $main::_EMBEDED = 0;
1343          } elsif (length $content) {
1344            $r = "<pre>@{[&escape ($content)]}</pre>";
1345          } else {
1346            $r = &text_to_html ("[INS[\n埋め込まれている [[$name]] はまだ書かれていません。\n]INS]\n", content_format => 'SuikaWiki/0.9');
1347          }
1348        } else {    ## nested #EMBED
1349          $r = &text_to_html ("[INS[\n[[$name]] の埋め込みは (入り組んでいるので) 解決されませんでした。\n]INS]\n", content_format => 'SuikaWiki/0.9');
1350        }
1351        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>);
1352      } elsif ($embedded =~ /^\[\[\#randomlink:(.+)\]\]$/) {
1353        return qq(<a href="$url_cgi?mycmd=RandomJump;x-param=@{[time.[0..9]->[rand 10]]}" class="wiki randomlink">$1</a>);
1354      } else {
1355        return $embedded;
1356      }
1357    }
1358    
1359    # Walrus add (5) start
1360    sub do_interwiki_box {
1361        my $remoteurl = $interwiki{$form{'myintername'}};
1362        if ($remoteurl) {
1363            $remoteurl =~ s/\b(euc|sjis|ykwk|asis|isbn)\(\$1\)/&interwiki_convert($1, $form{'mylocalname'})/e;
1364            print "Location: $remoteurl\n\n";
1365            exit(1);
1366        } else {
1367            &do_read;
1368        }
1369    }
1370    # Walrus add (5) end
1371    
1372  =head1 作者  # Walrus add (5) start
1373    sub make_interwiki_box {
1374        my ($localname, $intername) = @_;
1375        my %ignoretype = (
1376            'box'      => 'text',
1377            'text'     => 'text',
1378            'pass'     => 'password',
1379            'password' => 'password'
1380        );
1381        my $converted = ($ignoretype{$localname}) ? <<EOD : undef;
1382    <form action="$url_cgi" method="post">
1383        <input type="hidden" name="mycmd" value="interwikibox">
1384        <input type="hidden" name="mypage" value="$form{mypage}">
1385        <input type="hidden" name="myintername" value="$intername">
1386        $intername:
1387        <input type="$ignoretype{$localname}" name="mylocalname" value="" size="10">
1388        <input type="submit" value="Submit">
1389    </form>
1390    EOD
1391    }
1392    # Walrus add (5) end
1393    
1394      Copyright (C) 2000 by Hiroshi Yuki.  sub code_convert {
1395      結城浩 <hyuki@hyuki.com>      my ($contentref, $code) = (shift, shift || $kanjicode);
1396      http://www.hyuki.com/      $code = 'jis' if $code =~ /iso/;
1397      http://www.hyuki.com/yukiwiki/      $code = 'euc' if $code =~ /euc/;
1398        $code = 'sjis' if $code =~ /shift/;
1399        $code = 'utf8' if $code =~ /utf/;
1400    #   &Jcode::convert($contentref, $code);       # for Jcode.pm
1401        &jcode::convert($contentref, $code);       # for jcode.pl
1402        return $$contentref;
1403    }
1404    
1405    sub test_convert {
1406        my $txt = &text_to_html(<<"EOD", toc=>1);
1407    *HEADER1
1408    **HEADER1-1
1409    -ITEM1
1410    -ITEM2
1411    -ITEM3
1412    PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1413    PAR1PAR1PAR1PAR1PAR1PAR1''BOLD''PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1414    PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1415    
1416    PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2
1417    PAR2PAR2PAR2PAR2PAR2PAR2'''ITALIC'''PAR2PAR2PAR2PAR2PAR2PAR2PAR2
1418    PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2
1419    **HEADER1-2
1420    :TERM1:DESCRIPTION1 AND ''BOLD''
1421    PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1422    PAR1PAR1PAR1PAR1PAR1PAR1''BOLD''PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1423    PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1424    :TERM2:DESCRIPTION2
1425    :TERM3:DESCRIPTION3
1426    ----
1427    *HEADER2
1428    **HEADER2-1
1429    http://www.hyuki.com/
1430    **HEADER2-2
1431    
1432  質問、意見、バグ報告は hyuki@hyuki.com にメールしてください。  [[YukiWiki2]]
1433    
1434  =head1 配布条件  PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1435    PAR1PAR1PAR1PAR1PAR1PAR1'''''BOLD ITALIC'''''PAR1PAR1PAR1PAR1PAR1
1436    PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1PAR1
1437    >PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2
1438    >PAR2PAR2PAR2PAR2PAR2PAR2'''ITALIC'''PAR2PAR2PAR2PAR2PAR2PAR2PAR2
1439    >PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2PAR2
1440    
1441    LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0LEVEL0
1442    
1443    >LEVEL1
1444    >LEVEL1
1445    >LEVEL1
1446    >>LEVEL2
1447    >>LEVEL2
1448    >>LEVEL2
1449    >>>LEVEL3
1450    -HELLO-1
1451    --HELLO-2
1452    (HELLO-2, HELLO-2, HELLO-2)
1453    ---HELLO-3
1454    (HELLO-3, HELLO-3, HELLO-3)
1455    --HELLO-2
1456    ---HELLO-3
1457    --HELLO-2
1458    ---HELLO-3
1459    >>>LEVEL3
1460    >>>LEVEL3
1461    >>>LEVEL3
1462    >>>LEVEL3
1463    EOD
1464        print $txt;
1465        exit;
1466    }
1467    
1468  YukiWikiは、  sub do_diff {
1469  GNU General Public Licenseにて公開します。      if (not &is_editable($form{mypage})) {
1470            &do_read;
1471            return;
1472        }
1473        &open_diff;
1474        my $title = $form{mypage};
1475        &print_header($title, -noindex => 1);
1476        $_ = &escape($diffbase{$form{mypage}});
1477        &close_diff;
1478        print qq(<h3>$resource{difftitle}</h3>);
1479        print qq($resource{diffnotice});
1480        print qq(<pre class="diff">);
1481        foreach (split(/\n/, $_)) {
1482            if (/^\+(.*)/) {
1483                print qq(<b class="added">$1</b>\n);
1484            } elsif (/^\-(.*)/) {
1485                print qq(<s class="deleted">$1</s>\n);
1486            } elsif (/^\=(.*)/) {
1487                print qq(<span class="same">$1</span>\n);
1488            } else {
1489                print qq|??? $_\n|;
1490            }
1491        }
1492        print qq(</pre>);
1493        print qq(<hr>);
1494        &print_footer($title);
1495    }
1496    
1497  YukiWikiはフリーソフトです。  sub do_rss {
1498  ご自由にお使いください。      my $rss = new Yuki::RSS(
1499  自分好みのYukiWikiが作れるようにシンプルにしてあります。          version => '1.0',
1500            encoding => $charset,
1501        );
1502        $rss->channel(
1503            title => $modifier_rss_title,
1504            link  => $modifier_rss_link,
1505            description => $modifier_rss_description,
1506        );
1507        my $recentchanges = $database{$RecentChanges};
1508        my $count = 0;
1509        foreach (split(/\n/, $recentchanges)) {
1510            last if ($count >= 15);
1511            /^\- \d\d\d\d\-\d\d\-\d\d \([^)]+\) \d\d:\d\d:\d\d (\S+)/;    # date format.
1512            my $title = &unarmor_name($1);
1513            my $escaped_title = &escape($title);
1514            my $link = $modifier_rss_link . '?' . &encode($title);
1515            my $description = $escaped_title . &escape(&get_subjectline($title));
1516            $rss->add_item(
1517                title => $escaped_title,
1518                link  => $link,
1519                description => $description,
1520            );
1521            $count++;
1522        }
1523        # print RSS information (as XML).
1524        print <<"EOD"
1525    Content-type: text/xml
1526    
1527  =head1 謝辞  @{[$rss->as_string]}
1528    EOD
1529    }
1530    
1531  本家のWikiWikiを作ったCunningham & Cunningham, Inc.に  sub is_exist_page {
1532  感謝します。      my ($name) = @_;
1533        if ($use_exists) {
1534            return exists($database{$name});
1535        } else {
1536            return $database{$name};
1537        }
1538    }
1539    
1540  YukiWikiを楽しんで使ってくださる  sub __get_database ($) { $database{ $_[0] } }
 ネット上の方々に感謝します。  
1541    
1542  YukiWikiのロゴをデザインしてくださった橋本礼奈さん  package wiki::referer;
1543  http://city.hokkai.or.jp/~reina/  sub add ($$) {
1544  に感謝します。    my $page = shift;
1545      my $uri = shift;
1546      unless (ref $uri) {
1547        require URI;
1548        $uri = URI->new ($uri);
1549        ## Some schemes do not have query part.
1550        eval q{ $uri->query (undef) if $uri->query =~ /^[0-9]{6,8}$/ };
1551        $uri->fragment (undef);
1552      }
1553      $uri = $uri->canonical;
1554      return unless $uri;
1555      for my $regex (&get_dont_record) {
1556        return if $uri =~ /$regex/;
1557      }
1558      my %list = get ($page);
1559      $list{ $uri }++;
1560      set ($page, \%list);
1561    }
1562    sub get ($) {
1563      my $page = shift;
1564      split /"/, main::get_info ($page, 'Referer');
1565    }
1566    sub set ($%) {
1567      my $page = shift;
1568      my $list = shift;
1569      main::set_info ($page, Referer => join '"', %$list);
1570    }
1571    
1572    sub get_dont_record () {
1573      map {s/\$/\\\$/g; s/\@/\\\@/g; $_}
1574      grep !/^#/,
1575      split /[\x0D\x0A]+/, &main::__get_database ('RefererDontRecord');
1576    }
1577    sub get_site_name () {
1578      my @lines = grep /[^#]/, split /[\x0D\x0A]+/, &main::__get_database('RefererSiteName');
1579      my @item;
1580      for (@lines) {
1581        next if /^#/;
1582        my ($uri, $name) = split /\s+/, $_, 2;
1583        $uri =~ s/\$/\\\$/g;  $uri =~ s/\@/\\\@/g;  $uri =~ s/\//\\\//g;
1584        $name =~ s!([()/\\])!\\$1!g;  $name =~ s/\$([0-9]+)/).__decode (\${$1}).q(/g;
1585        push @item, [$uri, qq(q($name))];
1586      }
1587      @item;
1588    }
1589    
1590    sub list_html ($) {
1591      my $page = shift;
1592      my %list = get ($page);
1593      my $r = '';
1594      my @name = get_site_name;
1595      for my $uri (sort keys %list) {
1596        my $title;
1597        for my $item (@name) {
1598          if ($uri =~ /$item->[0]/) {
1599            $title = $uri;
1600            eval qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e}
1601              or die $@ ;#. qq{\$title =~ s/^.*$item->[0].*\$/$item->[1]/e};
1602            last;
1603          }
1604        }
1605        my $euri = main::escape ($uri);
1606        if ($title) {
1607          $r .= qq(<li>[$list{$uri}] <a href="$euri" title="URI: &lt;$euri>">@{[main::escape ($title)]}</a></li>\n);
1608        } else {
1609          $r .= qq(<li>[$list{$uri}] &lt;<a href="$euri">$euri</a>&gt;</li>\n);
1610        }
1611      }
1612      $r ? qq(<ul>$r</ul>\n) : '';
1613    }
1614    
1615  tieを使った版の元になるコードを送ってくださった  sub __decode ($) {
1616  「極悪」さんに感謝します。    my $s = shift;
1617      $s =~ tr/+/ /;
1618      $s =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/chr hex $1/ge;
1619      main::code_convert (\$s);
1620    }
1621    
1622  =head1 参照リンク  1;
1623    __END__
1624    =head1 NAME
1625    
1626  =over 4  wiki.cgi - This is YukiWiki, yet another Wiki clone.
1627    
1628  =item *  =head1 DESCRIPTION
1629    
1630  YukiWikiホームページ  YukiWiki is yet another Wiki clone.
 http://www.hyuki.com/yukiwiki/  
1631    
1632  =item *  YukiWiki can treat Japanese WikiNames (enclosed with [[ and ]]).
1633    YukiWiki provides 'InterWiki' feature, RDF Site Summary (RSS),
1634    and some embedded commands (such as [[#comment]] to add comments).
1635    
1636  本家のWikiWiki  Read F<readme_en.txt> (English) or F<readme_ja.txt> (Japanese) in more detail.
 http://c2.com/cgi/wiki?WikiWikiWeb  
1637    
1638  =item *  =head1 AUTHOR
1639    
1640  本家のWikiWikiの作者(Cunningham & Cunningham, Inc.)  Hiroshi Yuki <hyuki@hyuki.com> http://www.hyuki.com/yukiwiki/
 http://c2.com/  
1641    
1642  =item *  =head1 LICENSE
1643    
1644  YukiWikiのロゴデザインをしてくださった橋本礼奈さんのページ  Copyright (C) 2000-2002 by Hiroshi Yuki.
 http://city.hokkai.or.jp/~reina/  
1645    
1646  =back  This program is free software; you can redistribute it and/or
1647    modify it under the same terms as Perl itself.
1648    
1649  =cut  =cut

Legend:
Removed from v.1.4  
changed lines
  Added in v.1.31

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24