<?php

//**********************************************************************
//
// common routine
//
// (C) Copyright GOMI Hisashi 2002-2011 All rights reserved.
//
//**********************************************************************


//**************************************************
//
// variable
//
//**************************************************

//******************************
// statistics
//******************************

$dbhost = 'localhost';
$dbuser = 'mymanuke';
$dbpass = 'h2no3';
$dbname = 'mymanuke';

define("SCREEN_TOP", 0);
define("SCREEN_REVIEW", 1);
#define("SCREEN_GAMES", 2);
#define("SCREEN_ARCHIVES", 3);
#define("SCREEN_ABOUTUS", 4);
define("SCREEN_ABOUTUS", 2);

#$tabncthtml = array(
#  "<A href=\"/\">表 top</A>", "<A href=\"/review/list.php\">評 reviews</A>", "<A href=\"/archives/\">庫 archives</A>", "<A href=\"/about.php\">称 about us</A>"
#);
#$tabncthtml = array(
#  "<A href=\"/\">表 top</A>", "<A href=\"/review/list.php\">評 reviews</A>", "<A href=\"/games.php\">遊 games</A>", "<A href=\"/about.php\">称 about us</A>"
#);
#$tabncthtml = array(
#  "<A href=\"/\">表 top</A>", "<A href=\"/review/list.php\">評 reviews</A>", "<A href=\"/games.php\">遊 games</A>", "<A href=\"/archives/\">庫 archives</A>", "<A href=\"/about.php\">称 about us</A>"
#);
$tabncthtml = array(
  "<A href=\"/\">表 top</A>", "<A href=\"/review/list.php\">評 reviews</A>", "<A href=\"/about.php\">称 about us</A>"
);

#$tabacthtml = array(
#  "<B>表 top</B>", "<B>評 reviews</B>", "<B>庫 archives</B>", "<B>称 about us</B>"
#);
#$tabacthtml = array(
#  "<A href=\"/\"><B>表 top</B></A>", "<A href=\"/review/list.php\"><B>評 reviews</B></A>", "<A href=\"/games.php\"><B>遊 games</B></A>", "<A href=\"/about.php\"><B>称 about us</B></A>"
#);
#$tabacthtml = array(
#  "<B>表 top</B>", "<B>評 reviews</B>", "<B>遊 games</B>", "<B>庫 archives</B>", "<B>称 about us</B>"
#);
#$tabacthtml = array(
#  "<A href=\"/\"><B>表 top</B></A>", "<A href=\"/review/list.php\"><B>評 reviews</B></A>", "<A href=\"/games.php\"><B>遊 games</B></A>", "<A href=\"/archives/\"><B>庫 archives</B></A>", "<A href=\"/about.php\"><B>称 about us</B></A>"
#);
$tabacthtml = array(
  "<A href=\"/\"><B>表 top</B></A>", "<A href=\"/review/list.php\"><B>評 reviews</B></A>", "<A href=\"/about.php\"><B>称 about us</B></A>"
);


//**************************************************
//
// initialize
//
//**************************************************

mb_regex_encoding('UTF-8');

//**************************************************
//
// procedure
//
//**************************************************

//******************************
// db connect
//******************************
function db_connect()
{
  global $dbhost, $dbuser, $dbpass, $dbname;

  // connect to RDBM
  if ( !($my_con = mysqli_connect($dbhost, $dbuser, $dbpass)) ){
    $errmsg = mysqli_error($db);
    error($errmsg);
  }

  // select db
  if ( !mysqli_select_db($my_con, $dbname) ){
    $errmsg = mysqli_error($db);
    error($errmsg);
  }

  // 文字コード対策
  //db_query_update($my_con, "SET CHARACTER SET sjis");

  return $my_con;
}


//******************************
// db disconnect
//******************************
function db_disconnect($db)
{
  // disconnect from RDBM
  if ( !mysqli_close($db) ){
    $errmsg = mysqli_error($db);
    error($errmsg);
  }
}

//******************************
// db exec query
//******************************
function db_query($db, $sql)
{
  if ( !($result = mysqli_query($db, $sql)) ){
    $errmsg = quote_html(mysqli_error($db));
    $sql_quoted = quote_html($sql);
    error("system error: cannot execute query. [$errmsg] $sql_quoted");
  }
  return $result;
}

//******************************
// db exec query then update
//******************************
function db_query_update($db, $sql)
{
  $result = db_query($db, $sql);
  return mysqli_affected_rows($db);
}

//******************************
// db exec query and get single record
//******************************
function db_query_single_record($db, $sql)
{
  $result = db_query($db, $sql);
  $row = mysqli_fetch_array($result);
  mysqli_free_result($result);
  return $row;
}


//**************************************************
//
// quote library
//
//**************************************************

//******************************
// quote html
//******************************
function quote_html($str)
{
  $str = htmlspecialchars($str, ENT_NOQUOTES);
  //$str = mb_ereg_replace("&", "&amp;", $str);
  //$str = mb_ereg_replace("<", "&lt;", $str);
  //$str = mb_ereg_replace(">", "&gt;", $str);
  $str = nl2br($str);
  //$str = mb_ereg_replace("\n", "<BR>", $str);
  return $str;
}

function quote_html_return($str)
{
  $str = htmlspecialchars($str, ENT_NOQUOTES);
  //$str = mb_ereg_replace("&", "&amp;", $str);
  //$str = mb_ereg_replace("<", "&lt;", $str);
  //$str = mb_ereg_replace(">", "&gt;", $str);
  $str = mb_ereg_replace("\n", "<FONT color=\"blue\">CR/LF</FONT>", $str);
  //$str = mb_ereg_replace("\n", "<IMG src=\"back.gif\">", $str);
  return $str;
}

function quote_html_param($str)
{
  $str = mb_ereg_replace("&", "&amp;", $str);
  $str = mb_ereg_replace("\"", "&quot;", $str);
  //$str = htmlspecialchars($str, ENT_QUOTES);
  return $str;
}

function quote_html_textarea($str)
{
  $str = htmlspecialchars($str, ENT_NOQUOTES);
  //$str = mb_ereg_replace("&", "&amp;", $str);
  //$str = mb_ereg_replace("<", "&lt;", $str);
  //$str = mb_ereg_replace(">", "&gt;", $str);
  return $str;
}

//******************************
// quote sql
//******************************
function quote_sql_string($str)
{
  //return addslashes($str);
  //return mysqli_escape_string($str);
  //$str = mb_ereg_replace("\\\\", "\\\\", $str);
  //$str = mb_ereg_replace("\\\'", "\\\'", $str);
  //$str = mb_ereg_replace("\\\"", "\\\"", $str);
  // SJIS に特化したクォート
  $outputstr = "";
  for ( $i = 0, $n = strlen($str) ; $i < $n ; $i ++ ){
    $c = substr($str, $i, 1);
    if ( ord($c) < 128 ){
      // 半角
      if ( $c == "\\" || $c == "'" || $c == '"' ){
        $outputstr .= "\\" . $c;
      }else{
        $outputstr .= $c;
      }
    }else{
      // 全角
      $outputstr .= substr($str, $i, 2);
      $i ++;
    }
  }

  return $outputstr;
}

//******************************
// quote url
//******************************
// original code programmed by phpdoc@kreapc.de  05-Feb-2002 05:03
function url_callback($s)
{
  $linkstr = $s[0];

  if ($s[1]){
    $url = $s[1];
    return "<a href=\"$url\" target=_blank style=\"word-wrap:break-word;\">$linkstr</a>";
  }else
  if ($s[5]){
    $url = $s[5];
    return "<a href=\"mailto:$url\" style=\"word-wrap:break-word;\">$linkstr</a>";
  }else{
    return $linkstr;
  }
}

function url_replace($text)
{
  $text = preg_replace_callback(
    '/((https?|ftp|telnet):\/\/([\w.:?#@_=%\/+\-~]|(&amp;)|&)+)|'.
    '([\w_-]+(\.[\w_-]+)*@[\w_-]+(\.[\w_-]+)+)/',
    'url_callback', $text
  );
  //$text = mb_ereg_replace("/(s?https?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)", "<A href=\"\\1\" target=\"_blank\"><IMG src=\"jump.gif\" alt=\"\\1\" title=\"\\1\" border=\"0\"></A>", $child_message_quoted);
  return $text;
}

function url_count($text)
{
  return preg_match_all(
    '/((https?|ftp|telnet):\/\/([\w.:?#@_=%\/+\-~&]|(&amp;))+)|'.
    '([\w_-]+(\.[\w_-]+)*@[\w_-]+(\.[\w_-]+)+)/',
    $text, $out
  );
}


//**************************************************
//
// HTML format library
//
//**************************************************

$line_r = 3;
$line_color = "#804000";

//******************************
// HTML header
//******************************
function html_header($category = "", $tabno = 999, $title = "", $url = "", $description = "")
{
  global $tabacthtml, $tabncthtml;
  global $line_r, $line_color;
  global $json_ld;

  $title_str = "manuke.com";
  if ($category != "") {
    $title_str = $title_str . " [" . quote_html($category) . "]";
  }
  if ($title != "") {
    $title_str = quote_html($title) . " - " . $title_str;
  }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#">
<?php include_once("analyticstracking.php") ?>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META name="viewport" content="width=device-width,initial-scale=1">
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
<?php
if (isset($json_ld)) {
?><script type="application/ld+json">
<?php
  print(json_encode($json_ld, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
?></script>
<?php
}
?>
<TITLE><?php echo $title_str; ?></TITLE>
<META name="Classification" content="レビュー">
<META name="Description" content="本、マンガ、コンピュータ、時事ニュース、ゲーム、店など、あらゆるものをレビューして紹介するサイト">
<META name="KeyWords" content="レビュー,本,マンガ,コンピュータ,時事,ニュース,ゲーム,店,ノンフィクション,ルポ">
<meta property="og:type" content="article" />
<?php
if ($title != "") {
?><meta property="og:title" content="<?php echo quote_html($title); ?>" />
<?php
}
if ($url != "") {
?><meta property="og:url" content="<?php echo htmlentities(urlencode($url)); ?>" />
<?php
}
if ($description != "") {
?><meta property="og:description" content="<?php echo quote_html($description); ?>" />
<?php
}
?><meta property="og:image" content="https://manuke.com/image/pet_cat_oddeye.png" />
<meta property="og:site_name" content="manuke.com" />
<LINK rel="StyleSheet" href="/style.css" type="text/css" media="screen">
</HEAD>
<BODY bgcolor="#C8C8C8">
<TABLE border="0" valign="top" cellspacing="0" cellpadding="0" width="100%" height="100%">
 <TR>
  <TD class="title">
   <!-- nested table for title -->
   <TABLE border="0" cellspacing="0" cellpadding="0" width="100%" height="48">
   <TBODY>
    <TR>
     <TD width="168">
      <IMG src="/image/logo.gif" width="166" height="48" border="0">
     </TD>
     <TD align="right" valign="top" class="header"><A href="/review/rdf.php">評 review の RSS</A><BR><A href="/static/index.html">評 review の静的版</A> とその <A href="/~mysql/reviews.zip">zip</A> と <A href="/~mysql/reviews.tar.gz">tar.gz</A></TD>
    </TR>
   </TBODY>
   </TABLE>
   <!-- /nested table for title -->
  </TD>
 </TR>
 <TR>
  <TD class="tab">
   <!-- nested table for tab -->
   <TABLE border="0" cellspacing="0" cellpadding="0" height="40" width="100%">
   <TBODY>
    <TR width="100%"><?php
for ( $i = 0, $n = count($tabacthtml) ; $i < $n ; $i ++ ){
  print "<TD valign=\"bottom\"><TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"10\" height=\"$line_r\" bgcolor=\"$line_color\"><TR><TD></TD></TR></TABLE></TD>\n";
  if ( $i == $tabno ){
    $tabhtml = $tabacthtml[$i];
  }else{
    $tabhtml = $tabncthtml[$i];
  }
  if ( $i != $tabno ){
    print "<TD><TABLE border=\"0\" width=\"100%\" height=\"100%\" cellspacing=\"$line_r\" cellpadding=\"0\" bgcolor=\"$line_color\">";
    print "<TBODY><TR><TD bgcolor=\"#FFFFFF\" align=\"center\" style=\"padding: 8px;\" nowrap><FONT color=\"black\">$tabhtml</FONT></TD></TR></TBODY>";
    print "</TABLE></TD>\n";
  }else{
    print "<TD><TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"$line_r\" height=\"100%\" bgcolor=\"$line_color\"><TR><TD></TD></TR></TABLE></TD>\n";
    print "<TD valign=\"top\"><TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" height=\"100%\" bgcolor=\"$line_color\"><TR height=\"$line_r\"><TD></TD></TR><TR height=\"100%\"><TD bgcolor=\"#F0F0F0\" align=\"center\" style=\"padding: 8px;\" nowrap><FONT color=\"black\">$tabhtml</FONT></TD></TR><TR height=\"$line_r\" bgcolor=\"#F0F0F0\"><TD></TD></TR></TABLE></TD>\n";
    print "<TD><TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"$line_r\" height=\"100%\" bgcolor=\"$line_color\"><TR><TD></TD></TR></TABLE></TD>\n";
  }
}
print "<TD valign=\"bottom\" width=\"100%\"><TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" height=\"$line_r\" bgcolor=\"$line_color\"><TR><TD></TD></TR></TABLE></TD>\n";
?>
    </TR>
   </TBODY>
   </TABLE>
   <!-- /nested table for title -->
  </TD>
 </TR>
 <TR valign="top">
  <TD width="100%" height="100%" class="stuff">
   <!-- content -->
<?php
}


function html_header_gen($title)
{
  $title = quote_html($title);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META name="viewport" content="width=device-width,initial-scale=1">
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
<META name="Classification" content="レビュー">
<META name="Description" content="本、マンガ、コンピュータ、時事ニュース、ゲーム、店など、あらゆるものをレビューして紹介するサイト">
<META name="KeyWords" content="レビュー,本,マンガ,コンピュータ,時事,ニュース,ゲーム,店,ノンフィクション,ルポ">
<META name="GENERATOR" content="manuke.com review generator">
<TITLE><?php echo $title; ?> - manuke.com</TITLE>
</HEAD>
<BODY bgcolor="#eeeeee">
<!-- content -->
<?php
}


//******************************
// HTML buffer add footer
//******************************

function html_footer()
{
  global $line_r, $line_color;
?>
   <!-- /content --> 
  </TD>
 </TR>
 <TR width="100%" height="<?php print $line_r; ?>">
  <TD bgcolor="<?php print $line_color; ?>" width="100%"></TD>
 </TR>
 <TR>
  <TD align="right">Copyright &copy; manuke.com 2002-2024 All rights reserved.</TD>
 </TR>
</TABLE>
</BODY>
</HTML>
<?php
}


function html_footer_gen()
{
?>
<!-- /content -->
<P align="right"><A href="http://manuke.com/">manuke.com</A></P>
</BODY>
</HTML>
<?php
}


//**************************************************
//
// error output
//
//**************************************************

function error($msg)
{
  if ( ob_get_length() ){
    ob_end_clean();
  }
  html_header('error');
  echo $msg;
  html_footer();
  exit;
}


//**************************************************
//
// initial operation
//
//**************************************************

//******************************
// session
//******************************

if ( !isset($no_session) || $no_session == 0 ){
  session_start();
  // PHP < 4.1.0 のセッション変数定義
  //session_register('UserID');
  //session_register('AccessLevel');

  if ( isset($_SESSION['UserID']) ){
    $user_id = (int)$_SESSION['UserID'];
  }else{
    $user_id = 0;
  }
  if ( isset($_SESSION['AccessLevel']) ){
    $access_level = (int)$_SESSION['AccessLevel'];
  }else{
    $access_level = 0;
  }
}else{
  $no_log = 1;
}


//******************************
// database connection
//******************************
$db = db_connect();


//******************************
// log
//******************************

if ( !isset($no_log) || $no_log == 0 ){

  $session_id = session_id();
  $session_id_quoted = quote_sql_string($session_id);

  if ( $user_id > 0 ){
    $user_id_quoted = $user_id;
  }else{
    $user_id_quoted = "0";
  }

  $ip_address = getenv("REMOTE_ADDR");
  if ( $ip_address != '' ){
    $ip_address_or_null_quoted = "'$ip_address'";
  }else{
    $ip_address_or_null_quoted = "NULL";
  }

  $referer = getenv("HTTP_REFERER");
  if ( $referer != '' ){
    $referer_quoted = "'" . quote_sql_string($referer) . "'";
  }else{
    $referer_quoted = "NULL";
  }

  $request_uri = getenv("REQUEST_URI");
  if ( $request_uri != '' ){
    $request_uri_quoted = "'" . quote_sql_string($request_uri) . "'";
  }else{
    $request_uri_quoted = "NULL";
  }

  if ( $session_id <> '' ){
    // まずセッションID で調べる
    $sql = "SELECT UserID FROM AxsLog WHERE SessionID = '$session_id_quoted'";
    $row = db_query_single_record($db, $sql);
  }else{
    $row = false;
  }
  if ( $row != false ){
    // ログのカウントの更新
    $sql = <<<EOB
UPDATE
  AxsLog
SET
  AccessCount = AccessCount + 1
, LastAccessedDate = NOW()

EOB
;
    if ( $user_id > 0 && $row{'UserID'} == '' ){
      $sql .= ", UserID = $user_id_quoted" . "\n";
    }
    $sql .= "WHERE SessionID = '$session_id_quoted'";
    db_query_update($db, $sql);
  }else{
    // セッションID で調べられなかったら IP で調べる
    $sql = "SELECT UserID, FirstAccessedDate, IF(LastAccessedDate > FirstAccessedDate, LastAccessedDate, FirstAccessedDate) AS FinalAccessedDate FROM AxsLog WHERE IPAddress = '$ip_address' AND DATE_ADD(IF(LastAccessedDate > FirstAccessedDate, LastAccessedDate, FirstAccessedDate), INTERVAL 10 MINUTE) > NOW() ORDER BY FinalAccessedDate DESC LIMIT 0, 1";
    $row = db_query_single_record($db, $sql);
    if ( $row != false ){
      // ログのカウントの更新
      $sql = <<<EOB
UPDATE
  AxsLog
SET
  AccessCount = AccessCount + 1
, LastAccessedDate = NOW()

EOB
;
      if ( isset($session_id) && $session_id != "" ){
        $sql .= ", SessionID = '$session_id_quoted'" . "\n";
      }
      if ( $user_id > 0 && ($row{'UserID'} == '' || $row{'UserID'} == 0) ){
        $sql .= ", UserID = $user_id_quoted" . "\n";
      }
      $first_accessed_date = $row{'FirstAccessedDate'};
      $first_accessed_date_quoted = quote_sql_string($first_accessed_date);
      $sql .= "WHERE IPAddress = '$ip_address' AND FirstAccessedDate = '$first_accessed_date_quoted'";
      db_query_update($db, $sql);
    }else{
      // ログの新規作成
      $sql = <<<EOB
INSERT INTO AxsLog (
  SessionID
, UserID
, AccessCount
, FirstAccessedDate
, IPAddress
, HttpReferer
, RequestURI
) VALUES (
  '$session_id_quoted'
, $user_id_quoted
, 1
, NOW()
, $ip_address_or_null_quoted
, $referer_quoted
, $request_uri_quoted
)
EOB
;
      db_query_update($db, $sql);
    }
  }
}


?>
