<?php
//
// BBWA
// comment.php
// コメントを書き込む
// Teppei KAKU <teppei@sat.co.jp>
//

include("variables.php");
include("functions.php");

if (trim($_POST['repCom']) != "") {
  if (trim($_POST['repName']) == "") {
    $repName = "名前なし";
  } else {
    $repName = mb_convert_encoding($_POST['repName'], "EUC-JP", "auto");
  }
  $repCom = mb_convert_encoding($_POST['repCom'], "EUC-JP", "auto");
  $repCom = eregi_replace("\r\n|\r|\n", "{{BR}}", $repCom);
  $repCom = eregi_replace("<", "{{LT}}", $repCom);
  $repCom = eregi_replace(">", "{{GT}}", $repCom);

  $repTime = date("n/j G:i");

  $filePtr =
    fopen("${dirName}Messages/${_POST['repImg']}_mes.txt", "a");
  while (!flock($filePtr, LOCK_EX)) {};
  fwrite($filePtr, "${repName}|||${repCom}|||${repTime}\n");
  flock($filePtr, LOCK_UN);
  fclose($filePtr);

  // インデックスを修正
  $oldList = file("${dirName}INDEX");
  $filePtr = fopen("${dirName}INDEX", "w");
  while (!flock($filePtr, LOCK_EX)) {};
  foreach ($oldList as $listText) {
    $listText = trim($listText);
    if (!strstr($listText, $_POST['repImg'])) {
      fwrite($filePtr, "${listText}\n");
    } else {
      $piece = explode("|||", $listText);
    }
  }
  $listTime = time();
  $listText = "${_POST['repImg']}|||${listTime}|||${piece[2]}|||${piece[3]}\n";
  fwrite($filePtr, $listText);
  flock($filePtr, LOCK_UN);
  fclose($filePtr);

  if ($_POST['repCookie'] == "true" && trim($_POST['repName']) != "") {
    setcookie("REPNAME", $repName, mktime(0,0,0,1,1,2030));
  } else {
    setcookie("REPNAME", "", time() - 3600);
  }

  printHtml("コメントを投稿しました",
    "right.php?img=${_POST['repImg']}",
    "COM");
} else {
  printHtml("エラー: 本文を入力してください",
    "JavaScript:history.back()", "");
}
?>
