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

Legend:
Removed from v.1.8  
changed lines
  Added in v.1.41

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24