擬古猫といっしょ (gikoneko.php / gikonekoadd.php) 修正版
Together with Gikoneko - Modified version
========================================================

【日本語】

概要
----
kuzuhascript系BBS（あやしいわーるど系, patTemplate採用のPHP版BBS）向けの
「擬古猫といっしょ」占い機能。元は gikoneko.pl / gikonekoadd.cgi という
Perl CGIとして書かれていたものを PHP 8.3 に移植したもの。
本版は配布版に対して以下の修正を加えた修正版である。

修正内容
--------
1. 表示言語を conf.php の TEMPLATE_LANGUAGE 設定（'ja'/'en'）に連動させた。
   'en' に設定すると運勢ラベル・UI文言が英語になる。日英別ファイルは廃止し、
   1つのファイルで両言語に対応する（conf.php が無い場合は日本語で動作）。
   運勢ブロックは従来どおり1個ずつ独立しており（ラベルの日英は各ブロック
   内に持つ）、AAを追加する場合は elseif ブロックをひとつ書き足すだけでよい。
   普通の【吉】が一番よく出る出現率（11/25）もそのまま維持している。
2. データファイル（gikoneko_kotoba.dat）の位置を「PHPファイルと同じ
   ディレクトリ」に変更した。従来は ../cgi-bin/gikoneko_kotoba.dat を
   参照しており、その位置にファイルがないと書き込みが黙って失敗する
   （完了画面は出るのに保存されない）不具合の原因になっていた。
3. ホストチェック（$bbshost による「呼び出し元が不正です。」判定）を
   削除した。設置ドメインごとの書き換えが不要になった。
   ※本体側の BBSHOST 設定とは無関係に、本スクリプトはチェックを行わない。
4. 書き込みの成否を確認してから完了画面を出すようにした。失敗時は
   データファイルのパスを示すエラーを表示する。
5. データファイルが改行で終わっていない場合でも、新しいことばが
   最終行に連結されず、正しく新しい行として追記されるようにした。
6. ことばの長さをサーバー側でも検査するようにした（従来はブラウザの
   maxlength のみに依存していた）。
7. 運勢AAをif/elseif連鎖から $GIKO_FORTUNES データ配列に改めた。
   新しいAAの追加は配列の末尾に1項目足すだけでよく、日英ラベルも
   その項目内で完結する（詳細は「新しいAAの追加方法」を参照）。

新しいAAの追加方法
------------------
gikoneko.php 冒頭の $GIKO_FORTUNES 配列の末尾に、次の形の項目を
1つ追加するだけでよい。

    array(
        'label' => array( 'ja' => '【新吉】', 'en' => '[New Luck]' ),
        'aa' => "
    {label}
    　　　 ∧ ∧
    ～′￣(´ー`)＜{kotoba}
      UU￣ U  U
    ",
    ),

- {label}  … 表示言語に応じた運勢名に置換される。
- {kotoba} … ことばに置換される。複数書けば、それぞれ別のことばが入る
             （轟吉のように猫が複数いる場合に使う）。
- 'weight' => 数値 を付けると出現しやすさを変えられる（省略時1）。
- AA内に言語依存のセリフ（ﾊｯﾊｰﾝ! など）がある場合のみ、'aa' を
  array('ja' => "…", 'en' => "…") の形にする。それ以外は文字列1つでよい。
- AAは二重引用符文字列なので、" $ \ を使う場合は \" \$ \\ とする。

出典・ライセンス
----------------
本機能は以下の系譜を持つ。単一の起源から自然発生したものではなく、
複数の書き手による連続した創作の積み重ねであるため、その経緯をここに
明記する。

  1. 原型:【本店の点取り占い】（あやしいわーるど・非公認名義）
  2. Perl版実装 (gikoneko.pl / gikonekoadd.cgi): 石井博之
  3. PHP 8.3移植、および運勢AA・顔文字の大部分の意匠（擬古猫としての表現。
     一部、移植元スクリプトの時点で既に使われていた文字絵を含む）:
     MOTOI Kenkichi

Copyright (c) 2026 MOTOI Kenkichi

  - コード部分: MIT License
  - AA・顔文字部分: AAAPSが対象とする共有文化財に該当する。詳細は以下を参照。
    https://github.com/gikonekos/aaaps

本修正版は上記MIT Licenseの条件に従い、著作権表示・ライセンス表示を
保持したうえで改変・再配布するものである。

同梱ファイル
------------
- gikoneko.php        … 占い表示用の関数ライブラリ
                        （giko_lang / giko_fortune / giko_display）。
                        単体では何も出力しない。bbs.txt側からrequire_onceして使う。
- gikonekoadd.php     … 「擬古猫にことばを教える」投稿フォーム。
                        ブラウザから直接アクセスされる実行ファイル。
- gikoneko_kotoba.dat … 占いの言葉データファイル（テスト用の1行入り）。

必要な準備
----------
1. 同梱の gikoneko_kotoba.dat（占いの言葉を1行1件で並べたテキスト
   ファイル、UTF-8）を gikoneko.php / gikonekoadd.php と「同じ
   ディレクトリ」に置く。中身はテスト用の1行なので、好きに書き換えてよい。
   配置場所を変えたい場合は環境変数 GIKO_DATA_DIR でディレクトリを
   上書きできる（未設定時は __DIR__ を使用）。
2. データファイルにウェブサーバーからの書き込み権限を与える
   （例: chmod 666 gikoneko_kotoba.dat）。
3. 表示言語は conf.php の TEMPLATE_LANGUAGE に従う（'ja' または 'en'）。
   本スクリプト側での言語設定は不要。

bbs.txt側の修正箇所
--------------------
BBS本体（bbs.txt）のうち、未読メッセージ表示（$msgmore）を組み立てている
箇所を、以下のように書き換える（NO_UNREAD_MESSAGES で検索をかける）。

        else {
            require_once("./gikoneko.php");
            ob_start();
            giko_display();
            $msgmore = T('NO_UNREAD_MESSAGES') . ' ' . ob_get_clean();
        }

giko_display() 自体はecho出力のみを行う関数（戻り値を持たない）ため、
ob_start() / ob_get_clean() で文字列化して $msgmore の末尾に連結する。

注意点
------
- PHP 8.3 で動作確認済み。mb_*系関数は未使用（mbstring不要）。
- gikonekoadd.php は単体で完結する実行ファイル。conf.php を自分で読み込んで
  言語を判定するため、gikoneko.php とは独立して動作する。
- 投稿フォームには認証・スパム対策の類は一切ない。誰でも書き込める
  ことを前提とした機能なので、荒らされた場合は gikoneko_kotoba.dat を
  直接編集して掃除すること。

------------------------------------------------------------------------

[English]

Overview
--------
A "Together with Gikoneko" fortune-telling feature for kuzuhascript-style
BBS software (Ayashii World lineage; PHP BBS using patTemplate). Originally
written as Perl CGI scripts (gikoneko.pl / gikonekoadd.cgi), later ported
to PHP 8.3.

Every time a visitor has no unread messages, the BBS shows a random
ASCII-art cat (Gikoneko) delivering a random "fortune" phrase drawn from a
text file. Visitors can teach the cat new phrases through a submission form.

This package is a modified version of the distributed PHP port.

Changes in this version
-----------------------
1. The display language now follows the TEMPLATE_LANGUAGE setting
   ('ja'/'en') in conf.php. With 'en', fortune labels and UI text are in
   English. The separate Japanese/English file pairs are deprecated; a
   single set of files serves both languages (defaults to Japanese if
   conf.php is absent). Each fortune block remains self-contained as
   before (the ja/en labels live inside each block), so adding a new AA
   is still just a matter of pasting in one more elseif block. The
   original odds - plain 吉 being the most common draw at 11/25 - are
   kept as-is.
2. The data file (gikoneko_kotoba.dat) now lives in the SAME directory as
   the PHP files. The original looked for ../cgi-bin/gikoneko_kotoba.dat,
   and if the file wasn't there, writes silently failed (the success page
   appeared, but nothing was saved).
3. The host check ($bbshost / "invalid caller" rejection) has been removed.
   No per-domain configuration is needed. (This is independent of the
   BBSHOST setting in conf.php; these scripts perform no such check.)
4. The write result is now verified before the success page is shown.
   On failure, an error naming the data file path is displayed.
5. If the data file does not end with a newline, new words are no longer
   glued onto the last line; a newline is inserted automatically.
6. Word length is now also validated server-side (previously only the
   browser's maxlength attribute was relied on).
7. Fortunes were converted from an if/elseif chain to a $GIKO_FORTUNES
   data array. Adding new ASCII art is now a matter of appending one
   entry, with both language labels self-contained in that entry (see
   "Adding new ASCII art" below).

Adding new ASCII art
--------------------
Append one entry of the following form to the end of the $GIKO_FORTUNES
array at the top of gikoneko.php:

    array(
        'label' => array( 'ja' => '【新吉】', 'en' => '[New Luck]' ),
        'aa' => "
    {label}
    　　　 ∧ ∧
    ～′￣(´ー`)＜{kotoba}
      UU￣ U  U
    ",
    ),

- {label}  ... replaced with the fortune name for the active language.
- {kotoba} ... replaced with a fortune word. Write it multiple times and
               each occurrence gets its own word (used when there are
               multiple cats, as in Thunder Luck).
- Add 'weight' => N to make an entry more or less common (default 1).
- Only when the art contains language-specific speech (like "Ha-haan!")
  does 'aa' need to be array('ja' => "...", 'en' => "..."). Otherwise a
  single string is shared by both languages.
- The art is a double-quoted PHP string; escape " $ \ as \" \$ \\ if
  they appear in the art.

Origin and license
------------------
This feature is the product of successive contributions by multiple
authors rather than a single origin:

  1. Original concept: "Tentori Uranai" fortune-telling
     (Ayashii World, unofficial)
  2. Perl implementation (gikoneko.pl / gikonekoadd.cgi): Hiroyuki Ishii
  3. PHP 8.3 port, and most of the fortune ASCII art / kaomoji designs
     (the Gikoneko renditions; some art was already present in the Perl
     scripts being ported): MOTOI Kenkichi

Copyright (c) 2026 MOTOI Kenkichi

  - Code: MIT License
  - ASCII art / kaomoji: covered as shared cultural material under AAAPS.
    See: https://github.com/gikonekos/aaaps

This modified version is distributed under the terms of the MIT License,
retaining the copyright and license notices above.

Included files
--------------
- gikoneko.php        ... Fortune display library (giko_lang /
                          giko_fortune / giko_display). Outputs nothing on
                          its own; require_once it from the BBS.
- gikonekoadd.php     ... "Teach Gikoneko a word" submission form.
                          Accessed directly from the browser.
- gikoneko_kotoba.dat ... Fortune phrase data file (contains one test line).

Setup
-----
1. Place the bundled gikoneko_kotoba.dat (a UTF-8 text file with one
   fortune phrase per line) in the SAME directory as the PHP files. It
   ships with a single test line; feel free to rewrite it. To store it
   elsewhere, set the GIKO_DATA_DIR environment variable to the desired
   directory (defaults to __DIR__).
2. Make the data file writable by the web server
   (e.g. chmod 666 gikoneko_kotoba.dat).
3. The display language follows TEMPLATE_LANGUAGE in conf.php ('ja' or
   'en'). No language configuration is needed in these scripts.

BBS integration (bbs.txt)
-------------------------
In the BBS core (bbs.txt), find where the unread-message string ($msgmore)
is built (search for NO_UNREAD_MESSAGES) and rewrite it as:

        else {
            require_once("./gikoneko.php");
            ob_start();
            giko_display();
            $msgmore = T('NO_UNREAD_MESSAGES') . ' ' . ob_get_clean();
        }

giko_display() only echoes output (it returns nothing), so ob_start() /
ob_get_clean() are used to capture it as a string and append it to
$msgmore.

Notes
-----
- Tested on PHP 8.3. No mb_* functions are used (mbstring not required).
- gikonekoadd.php is a self-contained executable script. It loads conf.php
  itself to determine the language, and works independently of
  gikoneko.php.
- The submission form has no authentication or spam protection whatsoever.
  It is designed on the assumption that anyone may post. If it gets
  vandalized, clean up by editing gikoneko_kotoba.dat directly.
