<?php
class userActions extends sfMyActions {
  public $rootLink = '/';

 /**
  *==================== REGISTER AND CONFIRM ====================
  */
  public function executeRegister() {
    if ($this->getUser()->isAuthenticated()) return $this->redirect($this->rootLink);
    if ($this->getRequest()->getMethod() == sfRequest::POST) {
      $this->tbluser = new Tbluser();
      $this->tbluser->setUsUsername(trim($this->getRequestParameter('us_username')));
      $this->tbluser->setUsPassword(md5($this->getRequestParameter('us_password')));
      $this->tbluser->setUsFullname($this->getRequestParameter('us_fullname'));
      $this->tbluser->setUsSex((int)$this->getRequestParameter('us_sex'));
      $this->tbluser->setUsEmail($this->getRequestParameter('us_email'));
      $this->tbluser->setUsPhone($this->getRequestParameter('us_phone'));
      $this->tbluser->setUsSchool($this->getRequestParameter('us_school'));
      $this->tbluser->setUsProvince($this->getRequestParameter('us_province'));
      $this->tbluser->setUsRegisterDate(date('Y-m-d H:i:s'));
      $this->tbluser->setUsScore(sfConfig::get('app_user_start_point'));
      $this->tbluser->save();

      $password = $this->getRequestParameter('us_password');
      userMessage::sendConfirmEmail($this->tbluser, $password);
      $this->messageHeader = userMessage::$lastMessage;
      $this->setTemplate('reportreg');
    }
    return sfView::SUCCESS;
  }

  public function handleErrorRegister() {
    if ($this->getRequestParameter('us_username')===null) $this->getRequest()->removeAllError();
    return sfView::SUCCESS;
  }

  public function executeTerm() {
  }

  public function executeConfirm() {
    $active = $this->getRequestParameter('active');
    if ($active==null || strlen($active)!=32) return $this->forward404('Đường dẫn kích hoạt tài khoản không hợp lệ');
    $this->messageReturn = $this->rootLink;
    $this->setTemplate('report');

    $c = new Criteria();
    $c->add(TbluserPeer::US_IDMD5, $active);
    $this->tbluser = TbluserPeer::doSelectOne($c);
    if ($this->tbluser == null || $this->tbluser->getEmailConfirm() == 1) {
      $this->messageHeader = 'Thành viên này đã được xác nhận hoặc đã bị xóa !';
    } else {
      $this->tbluser->setUsScore($this->tbluser->getUsScore() + sfConfig::get('app_user_activate_point'));
      $this->tbluser->setEmailConfirm(1);
      $this->tbluser->save();
      $this->getUser()->signIn($this->tbluser);
      $this->messageHeader =
      'Chào mừng quý vị đến với web site Thư viện trực tuyến Violet! '.
      'Quý vị đã hoàn tất quá trình đăng ký thành công!';
    }
    return sfView::SUCCESS;
  }

 /**
  *==================== LOGIN AND LOGOUT ====================
  */
  public function executeLogin() {
    $this->ret = urldecode($this->getRequestParameter('ret'));
    if ($this->getUser()->isAuthenticated()) {
      return $this->loginFinish('Hệ thống đã được đăng nhập từ trước');
    }

    $username = $this->getRequestParameter('username');
    $password = $this->getRequestParameter('password');
    if ($username==null || $password==null) {
      if ($username!=null || $password!=null) { // is not the fist time
        if ($password==null) $this->getRequest()->setError('password', 'Please choose a password');
        if ($username==null) $this->getRequest()->setError('username', 'Please enter your username');
      }
      return sfView::SUCCESS;
    }

    // authentication with both username-password and email-password
    //
    $c = new Criteria();
    $c->add(TbluserPeer::US_USERNAME, trim($username));
    $this->tbluser = TbluserPeer::doSelectOne($c);
    if (!$this->tbluser) {
      $c = new Criteria();
      $c->add(TbluserPeer::US_EMAIL, trim($username));
      $this->tbluser = TbluserPeer::doSelectOne($c);
    }
    if (!$this->tbluser) {
      $this->getRequest()->setError('username', 'Username is incorrect');
      return sfView::SUCCESS;
    }
    if ($this->tbluser->getUsPassword() != md5($password) && $this->tbluser->getUsPassword() != $password) {
      $this->getRequest()->setError('password', 'Password is incorrect');
      return sfView::SUCCESS;
    }

    // check status and show message with inactive user
    // set default force to 1 for never show message
    //
    $force = $this->getRequestParameter('force', 0);
    if (!$force && $this->tbluser->getUsStatus() == 0) {
      $this->setTemplate('modifyEmail');
      return sfView::SUCCESS;
    }

    // signin symfony and remember login information
    //
    try {
      $remember = $this->getRequestParameter('remember');
      $this->getUser()->signIn($this->tbluser);
      $this->getUser()->rememberLogin($this->tbluser, $remember=='1');
      return $this->loginFinish('Đăng nhập thành công, xin chờ 1 chút');
    } catch (Exception $e) {
      $this->getRequest()->setError('username', $e->getMessage());
      return sfView::SUCCESS;
    }
  }

  public function loginFinish($message) {
    if (!preg_match('/^javascript:(.*)/', $this->ret, $match)) {
      $reload = $this->ret? "href='$this->ret'": 'reload()';
      return $this->renderText("<h3><font color='red'>$message</font></h3><script>Modalbox.hide(); window.location.$reload;</script>");
    } else {
      return $this->renderText("<h3><font color='red'>$message</font></h3><script>$match[1]</script>");
    }
  }

  /**
   * Modify user email if account cannot be activated
   *
   * @return unknown
   */
  public function executeModifyEmail() {
    $username = $this->getRequestParameter('username');
    $password = $this->getRequestParameter('password');
    $c = new Criteria();
    $c->add(TbluserPeer::US_USERNAME, $username);
    $this->tbluser = $tbluser = TbluserPeer::doSelectOne($c);
    if ($tbluser==null || $tbluser->getEmailConfirm()==1 || $tbluser->getUsPassword() != $password) {
      $this->messageHeader = 'Xin lỗi! Thông tin nhập không chính xác';
      $this->setTemplate('report');
      return sfView::SUCCESS;
    }

    $email = $this->getRequestParameter('us_email');
    if ($tbluser->getUsEmail() != $email) {
      $tbluser->setUsEmail($email);
      $c = new Criteria();
      $c->add(TbluserPeer::US_EMAIL, $email);
      if (TbluserPeer::doCount($c) >= 1) {
        $this->getRequest()->setError('us_email','Địa chỉ email này đã có thành viên khác đăng ký');
        return sfView::SUCCESS;
      }
      $tbluser->save();
    }

    userMessage::sendConfirmEmail($tbluser);
    $this->messageHeader = userMessage::$lastMessage;
    $this->setTemplate('reportreg');
    return sfView::SUCCESS;
  }

  public function handleErrorModifyEmail() {
    $c = new Criteria();
    $c->add(TbluserPeer::US_USERNAME, $this->getRequestParameter('username'));
    $this->tbluser = TbluserPeer::doSelectOne($c);
    $this->tbluser->setUsEmail($this->getRequestParameter('us_email'));
    return sfView::SUCCESS;
  }

  public function executeModifyPhone() {
    $username = $this->getRequestParameter('username');
    $password = $this->getRequestParameter('password');
    $c = new Criteria();
    $c->add(TbluserPeer::US_USERNAME, $username);
    $this->tbluser = $tbluser = TbluserPeer::doSelectOne($c);
    if ($tbluser==null || $tbluser->getMobileConfirm()==1 || $tbluser->getUsPassword() != $password) {
      $this->messageHeader = 'Xin lỗi! Thông tin nhập không chính xác';
      $this->setTemplate('report');
      return sfView::SUCCESS;
    }

    $phone = $this->getRequestParameter('us_phone');
    if ($tbluser->getUsPhone() != $phone) {
      $tbluser->setUsPhone($phone);
      $c = new Criteria();
      $c->add(TbluserPeer::US_PHONE, $phone);
      $this->tbluser2 = TbluserPeer::doSelectOne($c);
      if ($this->tbluser2) {
        $this->getRequest()->setError('us_phone','Số điện thoại này đã được đăng ký cho tài khoản khác');
        $this->setTemplate('modifyEmail');
        return sfView::SUCCESS;
      }
      $tbluser->save();
    }
    $this->setTemplate('modifyEmail');
  }

  public function handleErrorModifyPhone() {
    $c = new Criteria();
    $c->add(TbluserPeer::US_USERNAME, $this->getRequestParameter('username'));
    $this->tbluser = TbluserPeer::doSelectOne($c);
    $this->tbluser->setUsPhone($this->getRequestParameter('us_phone'));
    $this->setTemplate('modifyEmail');
    return sfView::SUCCESS;
  }

  public function executeLogout() {
    $this->getUser()->signOut();
    $ret = $this->getRequest()->getReferer();
    if (preg_match('@/(document|present|entry)/(create|edit|delete)@', $ret)) $ret = $this->rootLink;
    if (preg_match('@/(blog)/(createweb|updateweb|join)@', $ret)) $ret = $this->rootLink;
    if (preg_match('@/(test)/(try|create|do|finish|bank|input)@', $ret)) $ret = $this->rootLink;
    if (preg_match('@/(admin|message)(/.*)?$@', $ret)) $ret = $this->rootLink;
    return $this->redirect($ret);
  }

 /**
  *==================== FORGOT PASSWORD ====================
  */
  public function executeForgotpass() {
    $us_mail = $this->getRequestParameter('mail');
    if ($us_mail != null) {
      $c = new Criteria();
      $c->add(TbluserPeer::US_EMAIL, trim($us_mail));
      $tbluser = TbluserPeer::doSelectOne($c);
      if ($tbluser == null || $tbluser->getUsStatus() >= 4) {
        $this->getRequest()->setError('mail', 'Email không đúng hoặc tài khoản này đang bị khóa');
        return sfView::SUCCESS;
      }
      $sendOK = userMessage::sendForgotPassEmail($tbluser);
      $this->messageHeader = userMessage::$lastMessage;
      $this->messageReturn = $this->rootLink;
      $this->setTemplate('reportreg');
    }
    return sfView::SUCCESS;
  }

  public function handleErrorForgotpass() {
    return sfView::SUCCESS;
  }

  public function executeCheckphone() {
    $phone = $this->getRequestParameter('phone');
    $c = new Criteria();
    $c->add(TbluserPeer::US_PHONE, trim($phone));
    if (TbluserPeer::doCount($c) == 0) $msg = 'Số điện thoại này chưa được đăng ký trên Violet.vn';
    else $msg = 'Số điện thoại đã được đăng ký. Hãy thực hiện tiếp bước sau';
    $this->getRequest()->setError('phone', $msg);
    $this->setTemplate('forgotpass');
  }

  public function handleErrorCheckphone() {
    $this->setTemplate('forgotpass');
    return sfView::SUCCESS;
  }

  public function executeRequestpass()
  {
    $id = $this->getRequestParameter('id');
    $pwd = $this->getRequestParameter('pwd');
    $mail = $this->getRequestParameter('mail');
    $rand = $this->getRequestParameter('rand');
    if ($id == null || $pwd==null || strlen($pwd)!=32 || $mail==null || strlen($mail)!=32)
      $this->forward404('Đường dẫn lấy lại mật khẩu không hợp lệ');

    $c = new Criteria();
    $c->add(TbluserPeer::US_ID, $id);
    $c->add(TbluserPeer::US_EMAIL, "md5(US_EMAIL)='$mail'", Criteria::CUSTOM);
    $tbluser = TbluserPeer::doSelectOne($c);
    if (!$tbluser) $this->forward404('Thành viên không tồn tại hoặc đã bị xóa');

    if ($rand != md5($tbluser->getUsPassword())) {
      $this->messageHeader = 'Mật khẩu của quý vị đã được thay đổi, quý vị không thể sử dụng Email đổi mật khẩu này được nữa.';
    } else {
      $tbluser = TbluserPeer::retrieveByPK($tbluser->getUsId());
      $tbluser->setUsPassword($pwd);
      $tbluser->setEmailConfirm(1);
      $tbluser->save();
      $this->messageHeader = 'Mật khẩu của quý vị đã được thay đổi! Quý vị vui lòng xem lại email để lấy mật khẩu mới.';
      myUtility::log($tbluser->getUsFullname().' <'.$tbluser->getUsEmail().'> request new password completed', 'mail.log');
    }
    $this->messageReturn = $this->rootLink;
    $this->setTemplate('report');
    return sfView::SUCCESS ;
  }

 /**
  *==================== SHOW USER INFORMATION ====================
  */
  public function executeIndex() {
    $this->forward('user', 'list');
  }

  public function executeList() {
    $this->type = $this->getRequestParameter('type', 'all');
    $this->page = $this->getRequestParameter('page', 1);
    $this->mainBlog = (blogStore::$blogName == 'main');
    if ($this->mainBlog) {
      $c = new Criteria();
      $c->addDescendingOrderByColumn(TbluserPeer::US_ID);
      $this->pager = new PropelPager($c, 'TbluserPeer', 'doSelect', $this->page, 20);
    } else {
      $c = new Criteria();
      $c->add(TblbloguserPeer::US_BLOG, blogStore::$blogId);
      $c->add(TblbloguserPeer::US_ROLE, 1);
      $c->addDescendingOrderByColumn(TblbloguserPeer::US_JOINDATE);
      $this->pager = new PropelPager($c, 'TblbloguserPeer', 'doSelect', $this->page, 20);
    }
  }

  public function executeShow() {
    $this->user_id = $this->getRequestParameter('id', blogStore::$userId);
    $this->forwardUnless($this->user_id || blogStore::$userId, 'default', 'login');
    $this->tbluser = TbluserPeer::retrieveByPk($this->user_id);
    $this->forward404Unless($this->tbluser, 'Người dùng không tồn tại');
    $this->tblblogcheckinfo = $this->tbluser->getTblblogcheckinfo();
    $this->isMyId = ($this->user_id == blogStore::$userId);
  }

  public function executeEdit() {
    $this->tbluser = TbluserPeer::retrieveByPk(blogStore::$userId);
    $this->tblblogcheckinfo = $this->tbluser->getTblblogcheckinfo();
    $this->CreateEditData();
  }

  public function handleErrorUpdate() {
    $this->tbluser = TbluserPeer::retrieveByPk($this->getRequestParameter('user_id'));
    $this->tblblogcheckinfo = $this->tbluser->getTblblogcheckinfo();
    $this->UpdateUserFromRequest($this->tbluser, $this->tblblogcheckinfo);
    $this->CreateEditData();
    $this->setTemplate('edit');
    return sfView::SUCCESS;
  }

  public function executeUpdate() {
    $user_id = $this->getRequestParameter('user_id');
    $this->forward404Unless($user_id == blogStore::$userId, 'Bạn đã đăng nhập bằng một tài khoản khác');
    $this->tbluser = TbluserPeer::retrieveByPk($user_id);
    $this->tblblogcheckinfo = $this->tbluser->getTblblogcheckinfo();
    $this->UpdateUserFromRequest($this->tbluser, $this->tblblogcheckinfo);

    if ($this->tbluser->isColumnModified(TbluserPeer::US_EMAIL)) {
      $email = $this->tbluser->getUsEmail();
      if ($email != '') {
        $c = new Criteria();
        $c->add(TbluserPeer::US_EMAIL, $email);
        $c->add(TbluserPeer::US_ID, $this->tbluser->getUsId(), Criteria::NOT_EQUAL);
        if (TbluserPeer::doCount($c) >= 1) {
          $this->CreateEditData();
          $this->getRequest()->setError('us_email', 'Địa chỉ email này đã được đăng ký');
          $this->setTemplate('edit');
          return sfView::SUCCESS;
        }
      }
      $this->tbluser->setEmailConfirm(0);
    }

    if ($this->tbluser->isColumnModified(TbluserPeer::US_PHONE)) {
      $phone = $this->tbluser->getUsPhone();
      if ($phone != '') {
        $c = new Criteria();
        $c->add(TbluserPeer::US_PHONE, $phone);
        $c->add(TbluserPeer::US_ID, $this->tbluser->getUsId(), Criteria::NOT_EQUAL);
        if (TbluserPeer::doCount($c) >= 1) {
          $this->CreateEditData();
          $this->getRequest()->setError('us_phone', 'Số điện thoại này đã được đăng ký');
          $this->setTemplate('edit');
          return sfView::SUCCESS;
        }
      }
      $this->tbluser->setMobileConfirm(0);
    }

    try {
      if ($this->getRequest()->GetFileFromRequest(true, $this))
        $this->tbluser->getObject()->SaveAvatar($this);
    } catch (Exception $e) {
      $this->getRequest()->setError('us_avatar', $e->getMessage());
      return sfView::SUCCESS;
    }
    $this->tblblogcheckinfo->save();
    $this->tbluser->save();
    $this->redirect('/user/show');
  }

  public function CreateEditData() {
    $this->isDisabled = ($this->tbluser->getUsChecked()==1)? 'disabled': '';
    $this->provinceInfo = TblblogschoolsPeer::retrieveByPK($this->tblblogcheckinfo->getCiProvince());
    $this->districtInfo = TblblogschoolsPeer::retrieveByPK($this->tblblogcheckinfo->getCiDistrict());
    $this->schoolInfo   = TblblogschoolsPeer::retrieveByPK($this->tblblogcheckinfo->getCiSchool());

    //lay thông tin về combobox tinh, huyen, don vi
    $this->tblblogshools_province = Tblblogschools::getItem(0, 0);
    if ($this->districtInfo && $this->provinceInfo)
      $this->tblblogshools_district = Tblblogschools::getItem(1, $this->provinceInfo->getScId());
    if ($this->schoolInfo && $this->districtInfo && $this->provinceInfo) {
      $position_id = $this->tblblogcheckinfo->getCiPosition();
      $type = blogStore::getSchoolType($position_id);
      $this->tblblogschools_schools = Tblblogschools::getItem($type, $this->districtInfo->getScId(), $this->provinceInfo->getScId());
    }
    //lay selected cua ngay, thang, nam sinh
    $birthday = $this->tblblogcheckinfo->getCiBirthday('Y-m-d');
    $this->ci_day = date("d", strtotime($birthday));
    $this->ci_month = date("m", strtotime($birthday));
    $this->ci_year = date("Y", strtotime($birthday));
    $this->subjectid = explode(',', $this->tblblogcheckinfo->getCiSubject());
  }

  public function UpdateUserFromRequest(&$tbluser, &$tblblogcheckinfo)
  {
    if ($tbluser->getUsChecked() != 1) {
      $tbluser->setUsFullname($this->getRequestParameter('fullname'));
      $tbluser->setUsSex((int)$this->getRequestParameter('us_sex'));
    }
    $tbluser->setUsEmail($this->getRequestParameter('us_email', ''));
    $tbluser->setUsPhone($this->getRequestParameter('us_phone', ''));

    $school_id   = $this->getRequestParameter('ci_school', 0);
    $district_id = $this->getRequestParameter('ci_district', 0);
    $province_id = $this->getRequestParameter('ci_province', 0);
    $ci_birthday = $this->getRequestParameter('ci_year', '').'-'.
                   $this->getRequestParameter('ci_month', '').'-'.
                   $this->getRequestParameter('ci_day', '');
    $ci_pr       = $this->getRequestParameter('ci_pr', '');
    $ci_idnumber = $this->getRequestParameter('ci_idnumber', 0);
    $ci_position = $this->getRequestParameter('ci_position', 0);
    $ci_badge    = $this->getRequestParameter('badge1', '0').','.
                   $this->getRequestParameter('badge2', '0').','.
                   $this->getRequestParameter('badge3', '0');
    $ci_subject  = $this->getRequestParameter('ci_subject', '');

    if ($tbluser->getUsChecked()==0) {
      $tblblogcheckinfo->setCiBirthday($ci_birthday);
      $tblblogcheckinfo->setCiNumberid($ci_idnumber);
      $tblblogcheckinfo->setCiPosition($ci_position);
      $tblblogcheckinfo->setCiBadge($ci_badge);
      $tblblogcheckinfo->setCiSchool($school_id);
      $tblblogcheckinfo->setCiDistrict($district_id);
      $tblblogcheckinfo->setCiProvince($province_id);
    }
    $tblblogcheckinfo->setCiPr($ci_pr);
    $tblblogcheckinfo->setCiSubject($ci_subject);
  }

  public function executeChangeUser() {
    $this->forward404Unless(blogStore::$userId > 0);
    $this->tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);

    if ($this->getRequest()->getMethod() == sfRequest::POST) {
      $oldusername = $this->tbluser->getUsUsername();
      $username = trim($this->getRequestParameter('us_username'));
      $oldpassw = $this->getRequestParameter('oldpassword');
      $password = $this->getRequestParameter('us_password');
      if (md5($oldpassw) != $this->tbluser->getUsPassword()) {
        $this->getRequest()->setError('oldpassword', 'Old password is not correct');
        $this->tbluser->setUsUsername($username);
        return sfView::SUCCESS;
      }
      if ($username != $oldusername) {
        $c = new Criteria();
        $c->add(TblbloghostPeer::BH_BLOGNAME, $oldusername);
        $tblhost = TblbloghostPeer::doSelect($c);
        if ($tblhost != null) {
          $this->getRequest()->setError('us_username', 'This username can not be changed');
          return sfView::SUCCESS;
        }
        $this->tbluser->setUsUsername($username);
        $c = new Criteria();
    	  $c->add(TbluserPeer::US_USERNAME, $username);
    		$tbluser = TbluserPeer::doSelectOne($c);
    		if ($tbluser != null) {
    		  $this->getRequest()->setError('us_username', 'This username is already exists. Please choose another one');
    		  return sfView::SUCCESS;
    		}
        $this->tbluser->setUsHomepage(null);
        $this->tbluser->save();
        myUtility::log($oldusername.' -> '.$username, 'changeusername.log');
      }
      if ($password != null) {
        if ($this->getRequestParameter('password2') == null) {
    		  $this->getRequest()->setError('password2', 'Please retype the password');
    		  return sfView::SUCCESS;
        }
        $this->tbluser->setUsPassword(md5($password));
        $this->tbluser->setUsKey(rand(1, time()));
        $this->tbluser->save();
      }
      return $this->renderText("<h3>Đổi tên truy nhập/mật khẩu thành công</h3><script>Modalbox.hide();</script>");
    }
    return sfView::SUCCESS;
  }

  public function handleErrorChangeUser() {
    $username = $this->getRequestParameter('us_username');
    $this->tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
    if ($username===null) $this->getRequest()->removeAllError();
    else $this->tbluser->setUsUsername($username);
    return sfView::SUCCESS;
  }
 
  public function executeLoadSchool(){
    $id = $this->getRequestParameter('id', 0);
    $type = $this->getRequestParameter('type', 0);
    if ($type == 1)
      $this->message = 'Chọn Quận/Huyện';
    if ($type > 1) {
      $this->message = 'Chọn Đơn vị';
      $position_id = $this->getRequestParameter('position_id', 32);
      $type = blogStore::getSchoolType($position_id);
    }
    $this->options = Tblblogschools::getItemWithGuide($type, $id, $this->message);
  }

  public function executeLoadAddress() {
    $this->id = $this->getRequestParameter('id', 0);
    $this->province = Tblblogschools::getItemWithGuide(0, 0, 'Chọn Tỉnh/Thành');
  }

 /**
  *==================== SCORE CHART ====================
  */
  public function executeListscore() {
    $this->ids = $this->getRequestParameter('id', blogStore::$userId);
    if (!$this->ids) return sfView::NONE;
    $this->ids = explode(',', urldecode($this->ids));
    $this->type = $this->getRequestParameter('type', 'week');

    $users = TbluserPeer::retrieveByPKs($this->ids);
    $usernames = array();
    $this->ids = array();
    foreach ($users as $user) {
      $usernames[$user->getUsId()] = $user->getUsFullname();
      $this->ids[] = $user->getUsId();
    }

    $flashChart = new sfFlashMultiChart($this->ids, $usernames);

    switch ($this->type) {
      case 'week':
      case 'month':
        if ($this->type=='week')
          $week = date('Y-m-d', strtotime('-7 day'));
        else
          $week = date('Y-m-d', strtotime('-1 month'));
        $today = date('Y-m-d');
        $c = new Criteria();
        if (count($this->ids)==1)
          $c->add(TbluserdayscorePeer::UDSC_USER, $this->ids[0]);
        else
          $c->add(TbluserdayscorePeer::UDSC_USER, $this->ids, Criteria::IN);
        $c->add(TbluserdayscorePeer::UDSC_DATE, $week, Criteria::GREATER_EQUAL);
        $c->addAscendingOrderByColumn(TbluserdayscorePeer::UDSC_DATE);
        $tbluserdayscores = TbluserdayscorePeer::doSelect($c);
        foreach ($tbluserdayscores as $tbluserdayscore) {
          $flashChart->addData($tbluserdayscore->getUdscUser(),
            $tbluserdayscore->getUdscDate('d-m'), $tbluserdayscore->getUdscScore());
        }

        $c = new Criteria();
        if (count($this->ids)==1)
          $c->add(TblusertempscorePeer::UTSC_USER, $this->ids[0]);
        else
          $c->add(TblusertempscorePeer::UTSC_USER, $this->ids, Criteria::IN);
        $c->add(TblusertempscorePeer::UTSC_DATE, $today);
        $tblusertempscores = TblusertempscorePeer::doSelect($c);
        foreach ($tblusertempscores as $tblusertempscore) {
          $flashChart->addData($tblusertempscore->getUtscUser(),
            $tblusertempscore->getUtscDate('d-m'), $tblusertempscore->getUtscScore());
        }
        break;
      case 'all':
        break;
    }
    return $this->renderText( $flashChart->render() );
  }

  public function executeScorechart() {
    return sfView::SUCCESS;
  }

 /**
  *==================== CHECK DETAIL USER INFORMATION ====================
  */
  public function executeCheck() {
    $user_id = $this->getRequestParameter('id', 0);
    $type = $this->getRequestParameter('type', 0);
    $my_id = $this->getUser()->getUserId();
    $this->forward404Unless($user_id > 0, 'Thành viên này không tồn tại');
    $this->forward404Unless($my_id > 0);
    if ($type == 0) { //moi` dinh danh
      //check xem da nho bao nhieu nguoi dinh danh roi
      $c = new Criteria();
      $c->add(TblblogusercheckPeer::UC_USER, $my_id);
      $countCheckInvite = TblblogusercheckPeer::doCount($c);
      $checker = TbluserPeer::retrieveByPK($user_id);
      if ($countCheckInvite < 4 || $checker->getUsAclgroup() == 1) {
        $userCheck = TblblogusercheckPeer::retrieveByPK($my_id, $user_id);
        if ($userCheck == null) {
          $userCheck = new Tblblogusercheck();
          $userCheck->setUcUser($my_id);
          $userCheck->setUcChecker($user_id);
          $userCheck->setUcApprove($type);
          $userCheck->setUcCheckDate(date('Y-m-d H:i:s'));
          $userCheck->save();
        }//if ($userCheck == null)
        $this->message = "Mời thành công";
      } else {
        $this->message = "Quý vị đã nhờ 4 người xác thực rồi";
      }
    } elseif ($type == 1) {//dinh danh
      $userCheck = TblblogusercheckPeer::retrieveByPK($user_id, $my_id);
      if ($userCheck == null) {
        $userCheck = new Tblblogusercheck();
        $userCheck->setUcUser($user_id);
        $userCheck->setUcChecker($my_id);
      }//if
      $userCheck->setUcApprove($type);
      $userCheck->setUcCheckDate(date('Y-m-d H:i:s'));
      $userCheck->save();

      //kiem tra xem da du 2 lan check chua
      $c = new Criteria();
      $c->add(TblblogusercheckPeer::UC_USER, $user_id);
      $c->add(TblblogusercheckPeer::UC_APPROVE, 1);
      $countCheck = TblblogusercheckPeer::doCount($c);
      $checker = TbluserPeer::retrieveByPK($my_id);
      if ($countCheck >= 2 || $checker->getUsAclgroup() == 1) {//update vao bang user la da duoc dinh danh
        $tbluser = TbluserPeer::retrieveByPK($user_id);
        $tbluser->setUsChecked(1);
        $tbluser->save();

        /*insert user nay lam thanh vien cua trang rieng thuoc don vi minh neu co*/
        //lay thong ti truong, huyen, tinh
        $c = new Criteria();
        $c->add(TblblogcheckinfoPeer::CI_USERID, $user_id);
        $c->setLimit(1);
        $tblblogcheckinfo = TblblogcheckinfoPeer::doSelectJoinTbluser($c);
        $tblblogcheckinfo = $tblblogcheckinfo[0];
        if ($tblblogcheckinfo) {
          $province = $tblblogcheckinfo->getCiProvince();
          $district = $tblblogcheckinfo->getCiDistrict();
          $school = $tblblogcheckinfo->getCiSchool();
          foreach (array($school, $district, $province) as $office) {
            if (!$office) continue;
            $c = new Criteria();
            $c->add(TblblogPeer::BL_SCHOOL, $office);
            $tblblog = TblblogPeer::doSelectOne($c);
            if ($tblblog) { //blog existed
              $tblbloguser =  new Tblbloguser();
              $tblbloguser->setUsBlog($tblblog->getBlId());
              $tblbloguser->setUsUser($tblblogcheckinfo->getCiUserid());

              $tblbloguser->setUsRole(1);
              $tblbloguser->setUsLastvisit(date("Y-m-d H:i:s"));
              $tblbloguser->setUsJoindate(date("Y-m-d H:i:s"));
              $tblbloguser->setUsEmail($tblblogcheckinfo->getTbluser()->getUsEmail());
              $tblbloguser->setUsFullname($tblblogcheckinfo->getTbluser()->getUsFullname());
              $tblbloguser->setUsNickname($tblblogcheckinfo->getTbluser()->getUsUsername());
              $tblbloguser->setUsPicture($tblblogcheckinfo->getTbluser()->getUsAvatar());
              $tblbloguser->save();
            }
          }
        }//if ($tblblogcheckinfo)
      }//if ($countCheck >= 2)
      return $this->renderText("<h3><font color='red'>Xác thực thành công</font></h3><script>Modalbox.hide(); $('feedback$user_id').innerHTML='Đã xác thực';</script>");
    } elseif ($type == 2) {//tu choi xac thuc
      $userCheck = TblblogusercheckPeer::retrieveByPK($user_id, $my_id);
      if ($userCheck != null) $userCheck->delete();
      return $this->renderText("<h3><font color='red'>Từ chối xác thực</font></h3><script>Modalbox.hide(); $('feedback$user_id').innerHTML='Từ chối';</script>");
    }
  }

  public function executeConfirmCheck() {
    $this->executeShow();
  }

  public function executeSameUser() {
  }

 /**
  *==================== LIST USER'S RESOURCES AND COMMENTS ====================
  */
  public function executeListpost() {
    $this->entry_type = $this->getRequestParameter('entry_type', 'present');
    $this->showall = intval($this->getRequestParameter('showall', 1));
    $user_id = $this->getRequestParameter('user_id', blogStore::$userId);
    $this->tbluser = TbluserPeer::retrieveByPK($user_id);
    $this->forward404Unless($this->tbluser, 'Thành viên không tồn tại hoặc đã bị xóa!');

    $this->entry_types = sfConfig::get('app_entry_type');
    $this->type = $this->entry_types[$this->entry_type];
    $this->forward404Unless($this->type!==null, 'Yêu cầu không hợp lệ');

    $c = new Criteria();
    $c->add(TblblogentryPeer::ENTRY_USER, $user_id);
    if ($this->showall!=1) {
      $c->add(TblblogentryPeer::ENTRY_BLOG, blogStore::$blogId);
      $c->addIndex('entry_userblog');
    } else {
      $c->addIndex('userindex');
    }
    $c->add(TblblogentryPeer::ENTRY_TYPE, $this->type);
    $c->addDescendingOrderByColumn(TblblogentryPeer::ENTRY_MODIFYDATE);
    $this->page = $this->getRequestParameter('page', 1);
    $this->pager = new PropelPager($c, 'TblblogentryPeer', 'doSelect', $this->page, 18);

    $this->tblblogentrys = $this->pager->getResult();
  }

  public function executeListdown() {
    $this->entry_type = $this->getRequestParameter('entry_type', 'present');
    $user_id = $this->getRequestParameter('user_id', blogStore::$userId);
    $this->tbluser = TbluserPeer::retrieveByPK($user_id);
    $this->forward404Unless($this->tbluser, 'Thành viên không tồn tại hoặc đã bị xóa!');

    $this->page = $this->getRequestParameter('page', 1);
    switch ($this->entry_type) {
      case 'present':
        $c = new Criteria();
        $c->add(TbluserpresentationPeer::USPRE_USER, $user_id);
        $c->addDescendingOrderByColumn(TbluserpresentationPeer::USPRE_DATE);
        $this->pager = new PropelPager($c, 'TbluserpresentationPeer', 'doSelect', $this->page, 18);
        break;
      case 'document':
        $c = new Criteria();
        $c->add(TbluserdocumentPeer::USDOC_USER, $user_id);
        $c->addDescendingOrderByColumn(TbluserdocumentPeer::USDOC_DATE);
        $this->pager = new PropelPager($c, 'TbluserdocumentPeer', 'doSelect', $this->page, 18);
        break;
      default:
        $this->forward404();
    }
  }

  public function executeComment() {
    $this->user_id = $this->getRequestParameter('us_id', $this->getUser()->getUserId());
    $this->tbluser = TbluserPeer::retrieveByPK($this->user_id);
    if (!$this->tbluser) $this->forward404('Người dùng không tồn tại');

    $this->type = $this->getRequestParameter('type', 'today');
    switch ($this->type) {
      case 'today':
        $time = date('Y-m-d');
        break;
      case 'yesterday':
        $time = date('Y-m-d', strtotime('-1 day'));
        break;
      case 'thisweek':
        $time = date('Y-m-d', strtotime('-1 week'));
        break;
      default:
        $time = null;
        break;
    }

    $c = new Criteria();
    $c->add(TblblogentrycommentPeer::CM_USER, $this->user_id);
    if ($time > 0) $c->add(TblblogentrycommentPeer::CM_DATE, $time, Criteria::GREATER_EQUAL);
    $this->blog = $this->getRequestParameter('blog', 'all');
    if ($this->blog=='this')
      $c->add(TblblogentrycommentPeer::CM_BLOG, blogStore::$blogId);
    else $c->addIndex('user_date');
    $c->addDescendingOrderByColumn(TblblogentrycommentPeer::CM_DATE);

    $this->page = $this->getRequestParameter('page', 1);
    $this->pager = new PropelPager($c, 'TblblogentrycommentPeer', 'doSelect', $this->page, 20);
  }

  public function executeListtag() {
    $this->page = $this->getRequestParameter('page', 1);
    $this->pr_id = $this->getRequestParameter('pr_id');
    $this->blog_id = $this->getRequestParameter('blog_id', blogStore::$blogId);
    $this->user_id = $this->getRequestParameter('user_id', blogStore::$userId);
    $this->forward404Unless($this->blog_id && $this->user_id, 'Đường dẫn không hợp lệ');

    $c = new Criteria();
    if ($this->pr_id) $c->add(TblupdatelessonPeer::UPL_PRESENT, $this->pr_id);
    if ($this->blog_id != 'all') $c->add(TblupdatelessonPeer::UPL_BLOG, $this->blog_id);
    if ($this->user_id != 'all') $c->add(TblupdatelessonPeer::UPL_USER, $this->user_id);
    else if (!$this->pr_id) $c->add(TblupdatelessonPeer::UPL_USER, array(33, 13, 14, 226, 5498708, 7178467), Criteria::NOT_IN);
    $c->addDescendingOrderByColumn(TblupdatelessonPeer::UPL_DATE);
    $this->pager = new PropelPager($c, 'TblupdatelessonPeer', 'doSelect', $this->page, 18);
    $this->request_uri = '&user_id='. $this->user_id. '&blog_id='. $this->blog_id;
  }

 /**
  *==================== PAYMENT ====================
  */
  public function executePayment() {
    if ($this->getRequestParameter('submit')) {
      $url  = 'http://api.violet.vn/user/cardcharge';
      $post = 'src=Violet%2Evn';
      $post.= '&us_id='.blogStore::$userId;
      $post.= '&token='.md5(blogStore::$userId.'violet');
      $post.= '&type='.$this->getRequestParameter('cardtype');
      $post.= '&pin='.$this->getRequestParameter('cardcode');
      $post.= '&serial='.$this->getRequestParameter('cardserial');
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_POSTFIELDS => $post,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_USERAGENT => 'Violet.vn'
      ));
      $response = curl_exec($curl); 
      curl_close($curl);
      parse_str($response, $data);
      if ($data['status'] != '0') {
        $this->cardtype = $this->getRequestParameter('cardtype');
        $this->cardcode = $this->getRequestParameter('cardcode');
        $this->cardserial = $this->getRequestParameter('cardserial');
        $this->getRequest()->setError('cardtype', 'Lỗi nạp thẻ: '.$data['errMsg']);
      } else {
        $this->getRequest()->setError('message', 'Quý vị vừa nạp thành công thẻ mệnh giá '.myUtility::formatCurrency((int)$data['amount']).' + khuyến mại 100%');
      }
    }
    $this->tbluser = TbluserPeer::retrieveByPk(blogStore::$userId);
    $this->retLink = $this->getRequestParameter('retLink');
  }

  public function handleErrorPayment() {
    $this->tbluser = TbluserPeer::retrieveByPk(blogStore::$userId);
    $this->retLink = $this->getRequestParameter('retLink');
    $this->cardtype = $this->getRequestParameter('cardtype');
    $this->cardcode = $this->getRequestParameter('cardcode');
    $this->cardserial = $this->getRequestParameter('cardserial');
    if (!$this->getRequestParameter('submit')) $this->getRequest()->removeAllError();
    return sfView::SUCCESS;
  }

  public function executeBuyscore() {
    $this->tbluser = TbluserPeer::retrieveByPk(blogStore::$userId);
    $this->retLink = $this->getRequestParameter('retLink');
    $this->priceList = sfConfig::get('app_score_price');
    $this->buy = reset(array_keys($this->priceList));

    if ($this->getRequestParameter('submit')) {
      $amount = explode(':', $this->getRequestParameter('amount'));
      if ($amount[1] > $this->tbluser->getUsMoney()) {
        $this->getRequest()->setError('buy'.$amount[0], 'Không đủ tiền mua, hãy nạp thêm');
      } else {
        $this->tbluser->setUsScore($this->tbluser->getUsScore() + (int)$amount[0]);
        $this->tbluser->doTransaction(-$amount[1], 'pay', 'score '.$amount[0]);
      }
      $this->buy = (int)$amount[0];
    }
  }
 
 /**
  *==================== LOCK AND UNLOCK USER ====================
  */
  public function executeBan() {
    try {
      $user = sfContext::getInstance()->getUser();
      if (!$user->isAdministrator()) throw new myUserException('Bạn không có quyền khóa user');
      $this->user_id = $this->getRequestParameter('user_id');
      if ($this->user_id == $user->getUserId()) throw new myUserException('Bạn không thể tự khóa chính mình');

      $this->session_id = $this->getRequestParameter('session_id');
      $this->ban_time = $this->getRequestParameter('ban_time', 1);
      $this->confirm = $this->getRequestParameter('confirm');
      $this->tbluser = TbluserPeer::retrieveByPK($this->user_id);
      if (!$this->tbluser) throw new myUserException('Người dùng không tồn tại');

      if ($this->confirm == 'y') {
        if (-1 == $this->ban_time) {
          $this->tbluser->setUsStatus(8);
        } else {
          $status = $this->tbluser->getUsStatus();
          if ($status < 4) {
            $status += 4;
            $this->tbluser->setUsStatus($status);
            $this->tbluser->setUsLastvisited(date('Y:m:d H:i:s', strtotime($this->ban_time.'day')));
          }
        }
        $this->tbluser->save();
        if ($this->session_id) sfDatabaseSessionStorage::kickUser($this->session_id);
        else sfDatabaseSessionStorage::kickUserByName($this->tbluser->getUsUsername());

        $this->message = '<h3>Đã khóa nick và kick user khỏi hệ thống</h3>';
      }
    } catch (myUserException $e) {
      $this->confirm = 'y';
      $this->message = $e->getMessage();
    }
  }

  public function executeUnban() {
    try {
      if (!sfContext::getInstance()->getUser()->isAdministrator())
        throw new myUserException('Bạn không có quyền mở khóa user');
      $this->user_id = $this->getRequestParameter('user_id');
      $this->confirm = $this->getRequestParameter('confirm');
      $this->tbluser = TbluserPeer::retrieveByPK($this->user_id);
      if (!$this->tbluser) throw new myUserException('Người dùng không tồn tại');

      if ($this->confirm == 'y') {
        $status = $this->tbluser->getUsStatus();
        if ($status < 4) throw new myUserException('User này không bị khóa, không cần phải mở khóa');
        if ($status >= 8) $status = 0;
        if ($status >= 4) $status -= 4;

        $this->tbluser->setUsStatus($status);
        $this->tbluser->save();
        $this->message = '<h3>Đã khóa mở khóa cho user <b>'.$this->tbluser->getUsFullname().'</b> khỏi hệ thống</h3>';
      }
    } catch (myUserException $e) {
      $this->confirm = null;
      $this->message = $e->getMessage();
    }
  }

  public function executeCreateweb() {
    return $this->redirect('/blog/createweb');
  }
  public function executeListblogmember() {
    return $this->redirect('/user/list');
  }
  public function executeContact() {
    return $this->redirect('/blog/contact');
  }
  public function executeFaq() {
    return $this->redirect('/blog/faq');
  }
}
