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

Legend:
Removed from v.1.9  
changed lines
  Added in v.1.43

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24