<?php

class myUser extends sfBasicSecurityUser
{
  public function initialize($context, $parameters = null)
  {
    parent::initialize($context, $parameters);

    $storage = $this->getContext()->getStorage();
    $time = $storage->read(parent::LAST_REQUEST_NAMESPACE);
    if ($time == null && !$this->isAuthenticated()) $this->autoLogin();

    /*
    if ($this->isAuthenticated()) {
      $ip = myUtility::getRealIpAddr();
      $storeip = $this->getAttribute('userip', null, 'user');
      if ($storeip == null) $this->setAttribute('userip', $ip, 'user');
      else if ($storeip != $ip) {
        $this->setAuthenticated(false);
        session_regenerate_id(true);
      }
    }
    */
  }

  public function rememberLogin($user, $remember = false) {
    $value = $remember? base64_encode(serialize(array($user->getUsKey(), $user->getUsId()))): '';
    sfContext::getInstance()->getResponse()->setCookie('tvtl', $value, time() + 86400*15, '/');
  }

  public function autoLogin() {
    $remember = sfContext::getInstance()->getRequest()->getCookie('tvtl');
    if (!$remember) return;
    $info = unserialize(base64_decode($remember));
    if (is_array($info) && count($info)==2) {
      $c = new Criteria();
      $c->add(TbluserPeer::US_KEY, $info[0]);
      $c->add(TbluserPeer::US_ID, $info[1]);
      $tbluser = TbluserPeer::doSelectOne($c);
      try {
        if ($tbluser!=null) $this->signIn($tbluser);
      } catch (Exception $e) {}
    }
  }

  public function signIn($user) {
    $user->getObject()->checkUserLock();
    if (class_exists('sfDatabaseSessionStorage', false)) sfDatabaseSessionStorage::kickUserByName($user->getUsUsername());
    $this->setAuthenticated(true);
    $this->setAttribute('userid', $user->getUsId(), 'user');
    $this->setAttribute('username', $user->getUsUsername(), 'user');
    $this->setAttribute('userfullname', $user->getUsFullname(), 'user');
    $this->setAttribute('usertitle', $user->getObject()->getTitle(), 'user');
    $this->setAttribute('aclgroup', $user->getUsAclgroup(), 'user');
    $this->setAttribute('password', $user->getUsPassword(), 'user');
    $this->setAttribute('message', TblusermessagePeer::getUserUnread($user->getUsId()), 'user');

    if ($user->getUsAclgroup()=='1') $this->addCredential('moderator');
    $this->addCredential('user');
    $user->getObject()->onLogin();
  }

  public function signOut()
  {
    sfDatabaseOnlineUser::getInstance()->removeCurrentUser();
    $this->getAttributeHolder()->removeNamespace('user');

    $this->clearVote();
    $this->clearBlogmember();
    $this->clearManageCat();
    $this->setAuthenticated(false);
    $this->clearCredentials();
  }

  public function isAdministrator() {
    return $this->isAuthenticated() && $this->getAttribute('aclgroup', '', 'user') == '1';
  }

  public function getUserId() {
    if ($this->isAuthenticated()) return $this->getAttribute('userid', '', 'user');
    else return 0;
  }

  public function getUserName() {
    if ($this->isAuthenticated()) return $this->getAttribute('username', '', 'user');
    else return '';
  }

  public function getUserFullname() {
    if ($this->isAuthenticated()) return $this->getAttribute('userfullname', '', 'user');
    else return '';
  }

  public function getUserTitle() {
    if ($this->isAuthenticated()) return $this->getAttribute('usertitle', '', 'user');
    else return '';
  }

  public function getUnreadMessage() {
    if ($this->isAuthenticated()) return $this->getAttribute('message', '', 'user');
    else return 0;
  }

  /**
   * return type of sort of current user (date/download/rate)
   */
  public function getUserSort() {
    $request = sfContext::getInstance()->getRequest();
    return $request->getCookie('sort', 'date');
  }

  public function setUserSort($sort) {
    $response = sfContext::getInstance()->getResponse();
    $response->setCookie('sort', $sort, time()+60*60*24*15);
  }

  public function hasCredential($credentials, $useAnd = true) {
    if (!is_array($credentials)) {
      if ($credentials == 'blogadmin') return blogStore::isAdministator();
      if ($credentials == 'categorymod') return blogStore::canMod();
      if ($credentials == 'categorypost') return blogStore::canPost();
      if ($credentials == 'categorycomment') return blogStore::canComment();
      return parent::hasCredential($credentials, $useAnd);
    }
    $res = false;
    $stop = $useAnd? false: true;  // AND stop if false, OR stop if true
    foreach ($credentials as $credential) {
      $res = $this->hasCredential($credential, !$useAnd);
      if ($res == $stop) return $res;
    }
    return $res;
  }

  public function getManageCat() {
    if (!class_exists('blogStore')) return;
    if (!$this->isAuthenticated()) return '';
    $managecat = $this->getAttribute('managecat'.blogStore::$blogId);
    if ($managecat === null) {
      $managecat = TblbloguserPeer::getUserManageCat($this->getUserId());
      $this->setAttribute('managecat'.blogStore::$blogId, $managecat);
    }
    return $managecat;
  }

  public function clearManageCat() {
    if (!class_exists('blogStore')) return;
    $this->getAttributeHolder()->remove('managecat'.blogStore::$blogId);
  }

  /**
   * return true if this user is member of blog
   *
   * @return bool
   */
  public function isBlogMember() {
    if (!class_exists('blogStore')) return false;
    if (!$this->isAuthenticated()) return false;
    $isMember = $this->getAttribute('ismember'.blogStore::$blogId);
    if ($isMember===null) {
      $tblbloguser = TblbloguserPeer::retrieveByPK(blogStore::$blogId, blogStore::$userId);
      if ($tblbloguser == null) {
        $this->setIsBlogMember(false);
      } else {
        $this->setIsBlogMember($tblbloguser->getUsRole());
      }
      return $this->getAttribute('ismember'.blogStore::$blogId);
    } else return $isMember;
  }

  /**
   * Set current user is member of blog ($user_id==1) or not ($user_id==0)
   *
   * @param unknown_type $user_id
   */
  public function setIsBlogMember($is_member) {
    $this->setAttribute('ismember'.blogStore::$blogId, $is_member);
  }

  /**
   * Clear blogmember cookie information
   *
   */
  public function clearBlogmember() {
    if (!class_exists('blogStore')) return;
    $this->getAttributeHolder()->remove('ismember'.blogStore::$blogId);
  }

  /**
   * return status vote
   * false: never vote yet
   * true: voted
   * null: Nothing to vote
   */
  public function isVote() {
    if (blogStore::$tblblogpoll==null) return null;
    $cookieName = 'isvote'.blogStore::$tblblogpoll->getPollId();
    $isvote = $this->getAttribute($cookieName);
    if ($isvote === null) {
      $c = new Criteria();
      $c->add(TblblogpolldataPeer::PD_POLL, blogStore::$tblblogpoll->getPollId());
      $c->add(TblblogpolldataPeer::PD_IP, $_SERVER['REMOTE_ADDR']);
      $num = TblblogpolldataPeer::doCount($c);
      $this->setAttribute($cookieName, $num>0?1:0);
      return $num>0;
    } else return $isvote==1;
  }

  public function clearVote() {
    if (!class_exists('blogStore')) return;
    if (blogStore::$tblblogpoll==null) return;
    $cookieName = 'isvote'.blogStore::$tblblogpoll->getPollId();
    $this->getAttributeHolder()->remove($cookieName);
  }
}
