<?php
/* SVN FILE: $Id: Cookie.php 350 2008-05-11 22:55:05Z bb_yujiro $ */
/**
 * クッキー認証
 *
 * PHP versions 5
 *
 *      hitSuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 350 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-12 07:55:05 +0900 (月, 12 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * クッキー認証クラス
 *
 * @category        Authentication
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 350 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-12 07:55:05 +0900 (月, 12 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class Auth_AutoLogin_Cookie
{
    /**
     * クッキーの保持時間
     * @const integer
     */
    const LIFE_TIME = 1209600;

    /**
     * ログインキー
     * @const string
     */
    const LOGIN_KEY = 'loginkey';

    /**
     * クッキーの保持時間
     * @var integer
     */
    private $_lifetime = 0;

    /**
     * クッキーの削除時間
     * @var integer
     */
    private $_destroy = 0;

    /**
     * ログインキー
     * @var string
     */
    private $_loginkey;

    /**
     * DBオブジェクト
     * @var object
     */
    private $_objdb = null;

    /**
     * コンストラクタ
     *
     * @access public
     * @return void
     */
    public function __construct()
    {
        $this->_loginkey = empty($_COOKIE[self::LOGIN_KEY])?
                                     null:$_COOKIE[self::LOGIN_KEY];
        $this->_lifetime = time() + self::LIFE_TIME;
        $this->_destroy  = time() - 3600;
        $this->_objdb    = RKT_DB::getInstance();
    }

    /**
     * 自動ログイン
     *
     * @access public
     */
    public function autoLogin()
    {
        if (empty($this->_loginkey)){
            return false;
        }
        $status = RKT_account::exec()->getStatus();
        if ($status != STATUS_GUEST){
            return false;
        }

        $sql = 'SELECT ref_account FROM '.DB_PREFIX.'act_autologin '.
               'WHERE loginkey = :loginkey';
        $stmt = $this->_objdb->prepare($sql); 
        $stmt->execute(array(':loginkey'=> $this->_loginkey)); 
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        /* 取得結果の判定 */
        if (empty($result['ref_account'])){
            setcookie('loginkey', '', $this->_destroy, '/');
            RKT_account::exec()->accountDestroy();
            return false;
        }

        /* アカウント情報を取得できたか */
        if (!RKT_account::exec()->setAccount($result['ref_account'])){
            setcookie('loginkey', '', $this->_destroy, '/');
            RKT_account::exec()->accountDestroy();
            return false;
        }
        $this->setAutoLogin();

        return true;
    }
    
    /**
     * 自動ログインの設定
     *
     * @access public
     * @return boolean
     */
    public function setAutoLogin()
    {
        $sql = 'SELECT id FROM '.DB_PREFIX.'act_autologin '.
               'WHERE loginkey = :loginkey';
        $stmt = $this->_objdb->prepare($sql); 
        $stmt->execute(array(':loginkey'=> $this->_loginkey));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        
        $modified = date('Y-m-d H:i:s');
        $loginkey = $this->_getLoginKey();

        if ($this->_manip($result['id'])){
            setcookie('loginkey', $loginkey, $this->_lifetime, '/');
            $_SESSION['autologin'] = true;
        } else {
            setcookie('loginkey', '',$this->_destroy, '/');
            $_SESSION['autologin'] = false;
        }
        return $_SESSION['autologin'];
    }

    /**
     * 自動ログインテーブルの書き換え
     *
     * @access private
     * @return array ユーザーリクエスト
     */
    private function _manip($id)
    {
        $modified    = date('Y-m-d H:i:s');
        $loginkey    = $this->_getLoginKey();
        $ref_account = RKT_account::exec()->getAccountID();
        if (empty($id)){
            $sql = 'INSERT INTO '.DB_PREFIX.'act_autologin('.
                        ' modified, ref_account, loginkey) VALUES ('.
                        ':modified,:ref_account,:loginkey)';
            $stmt = $this->_objdb->prepare($sql); 
            $stmt->bindParam(':modified',    $modified,    PDO::PARAM_STR);
            $stmt->bindParam(':ref_account', $ref_account, PDO::PARAM_INT);
            $stmt->bindParam(':loginkey',    $loginkey,    PDO::PARAM_STR);
        } else {
            $sql = 'UPDATE '.DB_PREFIX.'act_autologin '.
                   'SET modified = :modified,ref_account = :ref_account,'.
                   'loginkey = :loginkey WHERE id = :id';
            $stmt = $this->_objdb->prepare($sql);
            $stmt->bindParam(':modified',    $modified,    PDO::PARAM_STR);
            $stmt->bindParam(':ref_account', $ref_account, PDO::PARAM_INT);
            $stmt->bindParam(':loginkey',    $loginkey,    PDO::PARAM_STR);
            $stmt->bindParam(':id',          $id,          PDO::PARAM_INT);
        }
        return $stmt->execute();
    }

    /**
     * ログインキー取得
     *
     * @access private
     * @return array ユーザーリクエスト
     */
    private function _getLoginKey()
    {
        $ref_account = RKT_account::exec()->getAccountID();
        $seed = $ref_account.time().$ref_account;

        $loginkey = RKT_Crypt::getHashed($seed);
        return $loginkey;
    }
} // Auth_AutoLogin_Cookie
?>