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

Diff of /suikawiki/script/wiki.cgi

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

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

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.47

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24