<?php

include_once('apps/blog/modules/entry/actions/actions.class.php');

class presentActions extends entryActions
{
  public function executeShow() {
    parent::executeShow();
    $this->tblpresentation = $this->tblblogentry->getTblpresentation();
    $this->forward404Unless($this->tblpresentation, 'Tài liệu gốc không tồn tại');
  }

  public function executeSame() {
    $this->forwardIf($this->getRequest()->getMethod() == sfRequest::GET, 'present', 'show');
    $this->executeShow();
    return $this->renderComponent('present', 'same', array('tblblogentry'=>$this->tblblogentry));
  }

  public function executeShowprint() {
    $this->executeShow();
    $this->setLayout(false);
  }

  public function executeCreate() {
    $this->tblpresentation = new Tblpresentation();
    $this->tblpresentation->setPrLesson($this->getRequestParameter('pr_lesson'));
    $this->createMethod = $this->getRequestParameter('createMethod', 'direct');
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->setTemplate('edit');
  }

  public function executeEdit() {
    $this->entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($this->entry_id);
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($tblblogentry->canEditEntry(), 'default', 'secure');
    $this->cat_id = $tblblogentry->getEntryCategory();
    $this->tblpresentation = $tblblogentry->getTblpresentation();
    $this->createMethod = 'direct';
    if ($this->tblpresentation->getPrLesson() === null) {
      $this->tblpresentation->setPrLesson(commonData::$lessons->getSimilar($this->tblpresentation->getPrCategory(), $this->tblpresentation->getPrName()));
    }
  }

  public function executeInsert() {
    $pr_id = $this->getRequestParameter('pr_id');
    $cat_id = $this->getRequestParameter('cat_id');
    $tblblogentry = TblblogentryPeer::insertSource($cat_id, $pr_id);
    if ($tblblogentry == null) {
      $this->getRequest()->setError('selection', 'Tài liệu bạn vừa chọn đã có trong trang riêng này rồi');
      $this->forward('present', 'create');
    }
    $this->redirect('/present/show?entry_id='.$tblblogentry->getEntryId());
  }

  public function executePaste() {
    $url = $this->getRequestParameter('entry_link', '');
    $cat_id = $this->getRequestParameter('cat_id');
    $catItem = blogStore::$catTree->getCatItem($cat_id);

    try {
      $match = preg_match('@/present/show[/\?]entry_id[/=](\d+)@', $url, $value);
      if (!$match) throw new Exception('Hãy copy từ một trang riêng violet.vn bất kỳ và paste vào đây');
      $tblblogentry = TblblogentryPeer::retrieveByPK($value[1]);
      if ($tblblogentry == null) throw new Exception('Tài liệu này không tồn tại');
      if ($tblblogentry->getEntryType() != $catItem->type) throw new Exception('Bạn phải chọn link của một ' . $catItem->getCatTypeName());
      $tblblogentry = TblblogentryPeer::insertSource($cat_id, $tblblogentry->getEntryLink());
      if ($tblblogentry == null) throw new Exception('Tài liệu đã có trong trang riêng này rồi');
      $this->redirect('/present/show?entry_id='.$tblblogentry->getEntryId());
    }
    catch (Exception $e) {
      $this->getRequest()->setError('entry_link', $e->getMessage());
      $this->forward('present', 'create');
    }
  }

  /**
   * Display predelete screen
   */
  public function executePredelete() {
    $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->forward404Unless($this->tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($this->tblblogentry->canDeleteEntry(), 'default', 'secure');

    if ($this->tblblogentry->canDeleteAll()) {
      $sql = 'select distinct entry_blog, (select bl_shortname from tblblog where bl_id=entry_blog)'.
      ' from tblblogentry where entry_link='.$this->tblblogentry->getEntryLink().
      ' and entry_status<2 and entry_type='.$this->tblblogentry->getEntryType();
      $this->tblblogs = myUtility::execSql($sql);
    }
  }

  /**
   * Delete entry (set status to 2)
   */
  public function executeDelete() {
    $all = $this->getRequestParameter('all');
    $tblblogentry = TblblogentryPeer::retrieveByPk($this->getRequestParameter('entry_id'));
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forwardUnless($tblblogentry->canDeleteEntry() && ($tblblogentry->canDeleteAll() || $all != 1), 'default', 'secure');
    myUtility::log('User '.blogStore::$userId.' delete '.($all==1? 'all ': '').'entry '.$tblblogentry->getEntryId(), 'deleted.log');
    $tblblogentry->deleteByUser($all == 1);
    return $this->renderModalbox('Đã xóa tài liệu thành công', $tblblogentry->getListUrl());
  }

  /**
   * Display predownload screen
   */
  public function executePredownload()
  {
    $pr_id = $this->getRequestParameter('pr_id');
    $presentation = TblpresentationPeer::retrieveByPk($pr_id);
    $this->forward404Unless($presentation, 'Tài liệu không tồn tại');

    $tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
    $this->usermoney = $tbluser->getUsMoney();
    $this->userscore = $tbluser->getUsScore();
    $this->presentscore = 1;

    if ($this->getRequestParameter('act') == null) {
      $this->act_link = '/present/download?pr_id='.$pr_id.'&t='.time();
      $this->act_opt = array();
      $this->act_name = 'tải';
    } else {
      $base = sfContext::getInstance()->getController()->genUrl('present/playsco', true);
      $this->act_link = $base.'/catId/'.$presentation->getPrCategory().'/packageId/'.$presentation->getPrId();
      $this->act_opt = array('target'=>'_blank', 'onclick'=>'location.reload();');
      $this->act_name = 'xem';
    }
    $this->price = $presentation->getPrPrice();
    if ($this->price) $this->setTemplate('charge');
  }

  /**
   * Download presentation
   */
  public function executeDownload()
  {
    $pr_id = $this->getRequestParameter('pr_id');
    $presentation = TblpresentationPeer::retrieveByPk($pr_id);
    $this->forward404Unless($presentation, 'Tài liệu không tồn tại');
    $tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
    userStatistics::recordDownloadPresent($tbluser, $presentation);

    $file_name = myUtility::vietDecode($presentation->getPrName());
    $file_name = preg_replace('@[^A-Za-z0-9 ]+@', '', $file_name);
    $file_path = $presentation->getObject()->getFullFileName(false);
    $code = 'dl'.abs(crc32($pr_id.'@'.$file_path));
    $_SESSION[$code] = 1;
    session_commit();

    $this->redirect(sfConfig::get('app_resource_root').'download.php?id='.$pr_id.
      '&path='.urlencode($file_path).
      '&file='.urlencode($file_name).
      '&user='.blogStore::$userId);
  }

  public function handleErrorUpdate() {
    if ($this->getRequestParameter('entry_id')) $this->executeEdit();
    else $this->executeCreate();
    $this->tblpresentation->setPrName($this->getRequestParameter('pr_name'));
    $this->tblpresentation->setPrLesson($this->getRequestParameter('pr_lesson'));
    $this->tblpresentation->setPrSource($this->getRequestParameter('pr_source'));
    $this->tblpresentation->setPrPrice($this->getRequestParameter('pr_price'));
    $this->setTemplate('edit');
    return sfView::SUCCESS;
  }

  /**
   * Create new, update or change information of presentation
   */
  public function executeUpdate()
  {
    if ($this->getRequest()->getMethod() != sfRequest::POST) $this->forward404();
    $this->createMethod = $this->getRequestParameter('createMethod', 'direct');
    $this->setTemplate('edit');

    myUtility::log("Execute update present ".$this->getRequestParameter('pr_name'), "uploads.log", "\n");
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->created = ($this->entry_id == null);
    $this->cat_id = $this->getRequestParameter('cat_id');

    if ($this->created) {
      $this->tblpresentation = new Tblpresentation();
    } else {
      $this->tblblogentry = TblblogentryPeer::retrieveByPk($this->entry_id);
      $this->tblpresentation = $this->tblblogentry->getTblpresentation();
      $this->forward404Unless($this->tblpresentation, 'Tài liệu không tồn tại');
      $this->forwardUnless($this->tblblogentry->canEditEntry(), 'default', 'secure');
    }
    $this->tblpresentation->setPrLesson($this->getRequestParameter('pr_lesson', -1));
    $this->tblpresentation->setPrName(myUtility::htmlToText($this->getRequestParameter('pr_name')));
    $this->tblpresentation->setPrSource(myUtility::htmlToText($this->getRequestParameter('pr_source')));
    $this->tblpresentation->setPrCategory(blogStore::$catTree->getCatItem($this->cat_id)->base);
    if ($this->tblpresentation->getPrUser() == null) $this->tblpresentation->setPrUser(blogStore::$userId);
    if ($this->tblpresentation->getPrUser() == blogStore::$userId) $this->tblpresentation->setPrDate(date('Y-m-d H:i:s'));
    if (($pr_price = $this->getRequestParameter('pr_price'))!==null) $this->tblpresentation->setPrPrice(max($pr_price, 0));

    try {
      if ($this->getRequest()->GetFileFromRequest(!$this->created, $this)) {
        $presentObj = new presentBase($this->tblpresentation);
        $presentObj->onUpload($this);
      }
    } catch (Exception $e) {
      myUtility::log(myUtility::mb_truncate_text($e->getMessage(), 60), "uploads.log");
      $this->getRequest()->setError('pr_filename', $e->getMessage());
      return sfView::SUCCESS;
    }

    try {
      if ($this->getRequest()->GetFileFromRequest(true, $this, 1)) {
        $thumbSrc = $this->getRequest()->CopyTempFile($this->uploaded, 'pre_thumbnail_'.$this->tblpresentation->getPrId().'.jpg');
        $this->tblpresentation->getObject()->onThumbUpload($thumbSrc);
        unlink($thumbSrc);
      }
    } catch (Exception $e) {
      $this->getRequest()->setError('pr_thumb', $e->getMessage());
      return sfView::SUCCESS;
    }

    try {
      $this->UpdatePresentDatabase();
    } catch (Exception $e) {
      Propel::close();
      $this->UpdatePresentDatabase(' (retry)');
    }
    if ($this->tblpresentation->getPrStatus()<2) {
      $this->redirect('/present/show?entry_id='.$this->tblblogentry->getEntryId());
    } else {
      $this->setTemplate('report');
      $this->messageHeader = 'Your presentation is uploaded, it will be processed in 3 minutes';
      $this->messageReturn = '/present/list?cat_id=' . $this->cat_id;
    }
  }

  /**
   * Update presentation into following tables:
   * tblpresentation, tblblogentry, tblblogcategoryentry, tbluser
   */
  public function UpdatePresentDatabase($try = '') {
    myUtility::log("Update database$try", "uploads.log");
    $this->tblpresentation->save();
    if ($this->created) {
      $this->tblblogentry = TblblogentryPeer::insertSource($this->cat_id, $this->tblpresentation->getPrId(), $this->tblpresentation->getPrStatus(), $this->tblpresentation->getPrLesson());
    } else {
      $this->tblblogentry->setEntryCategory($this->cat_id);
      $this->tblblogentry->save();
    }
    $this->tblpresentation->getTbluser()->incUpload();
    myUtility::log("Finish update present", "uploads.log");
  }

  public function executePlaysco()
  {
    $cmd = $this->getRequestParameter('cmd', '');
    $packageId = (int)$this->getRequestParameter('packageId');
    $catId = (int)$this->getRequestParameter('catId');
    $player = new SCORM13Player($packageId);
    if ($cmd == '') {
      $tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
      $presentation = TblpresentationPeer::retrieveByPk($packageId);
      userStatistics::recordDownloadPresent($tbluser, $presentation);
      $player->setBaseLink($this->getController()->genUrl('present/playsco'));
      $player->setDataPath("/uploads/resources/$catId/$packageId/".$presentation->getPrBaseDir());
    }
    $player->setUser($this->getUser()->getUserId(), $this->getUser()->getUserFullname());
    $player->setTemplate($this);
    return $player->execute($cmd);
  }

  public function executeGetlessonlisttag() {
    $cat_id = $this->getRequestParameter('cat_id');
    return $this->renderComponent('present', 'lessondropdown', array('cat_id'=>$cat_id));
  }

  public function executeSelectlesson() {
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->entry_id = $this->getRequestParameter('entry_id');
    $this->title = urldecode($this->getRequestParameter('title'));
    $this->catItem = blogStore::$catTree->getCatItem($this->cat_id);
  }

  public function executeSelectlessonlist() {
    $title = urldecode($this->getRequestParameter('title'));
    $cat_id = $this->getRequestParameter('cat_id');
    $cat_base = blogStore::$catTree->getCatItem($cat_id)->base;
    return $this->renderComponent('present', 'searchlesson', array('cat_base'=>$cat_base, 'title'=>$title));
  }

  public function findCatFromBase($catItem, $base) {
    foreach ($catItem->items as $key => $item) {
      if ($item->base == $base) return $key;
      if ($cat_id = $this->findCatFromBase($item, $base)) return $cat_id;
    }
    return null;
  }

  public function executeUpdatelesson() {
    $user_id = blogStore::$userId;
    $entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
    $pr_id = $tblblogentry->getEntryLink();
    $cat_id = $this->getRequestParameter('cat_id');
    $lesson = $this->getRequestParameter('lesson');
    $next = $tblblogentry->getNextUntagId();
    $catItem = blogStore::$catTree->getCatItem($cat_id);
    $title = ($lesson == -1)? 'ngoài SGK': commonData::$lessons->getTitle($catItem->base, $lesson);

    if (is_string($lesson) && preg_match('/\d+_\d+/', $lesson)) {
      $data = explode('_', $lesson);
      $base = intval($data[0]);
      $lesson = intval($data[1]);
      $cat_id = $this->findCatFromBase($catItem, $base);
      if (!$cat_id) return $this->renderText('<center>Lỗi: Không có thư mục con tương ứng</center>');
    } else {
      if ($cat_id != $tblblogentry->getEntryCategory()) $title = $catItem->name.'. '.$title;
    }

    $upl = TblupdatelessonPeer::retrieveByPk($user_id, $pr_id);
    if ($upl == null) {
      $upl = new Tblupdatelesson();
      $upl->setUplBlog(blogStore::$blogId);
      $upl->setUplUser(blogStore::$userId);
      $upl->setUplPresent($pr_id);
    }
    $upl->setUplFromcategory($tblblogentry->getEntryCategory());
    $upl->setUplCategory($cat_id);
    $upl->setUplLesson($lesson);
    $upl->setUplDate(date('Y-m-d H:i:s'));
    $upl->save();

    $c = new Criteria();
    $c->add(TblupdatelessonPeer::UPL_PRESENT, $pr_id);
    $tblupdates = TblupdatelessonPeer::doSelect($c);

    if ($tblblogentry->canEditEntry()) {
      $this->updateLesson($tblblogentry, $lesson, $cat_id, $tblupdates);
    } else {
      $total = count($tblupdates);
      if ($total >= sfConfig::get('sf_max_lesson_tagging')) {
        $same = 0;
        foreach ($tblupdates as $tblupdate) {
          if ($cat_id == $tblupdate->getUplCategory() && $lesson == $tblupdate->getUplLesson()) $same++;
        }
        if ($same / $total * 100 > sfConfig::get('sf_lesson_tagging_percent')) {
          $this->updateLesson($tblblogentry, $lesson, $cat_id, $tblupdates);
        }
      }
    }

    $nextLink = ($next? ' hoặc mở <a href="/present/show/entry_id/'.$next.'">bài tiếp theo...</a>': '');
    $resetLink = ($next? ' Chọn <a href="/present/resetlesson/entry_id/'.$entry_id.'">làm lại</a>': '');
    return $this->renderText('<center>Cảm ơn đã xác nhận tài liệu <b>'.$title.'</b>.'.$resetLink.$nextLink.'</center>');
  }

  public function executeResetlesson() {
    $entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
    if ($tblblogentry->canEditEntry()) {
      $tblpresentation = $tblblogentry->getTblpresentation();
      $tblpresentation->setPrLesson(null);
      $tblpresentation->save();
    }
    $this->redirect('/present/show?entry_id='.$entry_id);
  }

  public function updateLesson($tblblogentry, $lesson, $cat_id, $tblupdates) {
    $tblpresentation = $tblblogentry->getTblpresentation();
    $tblpresentation->setPrCategory(blogStore::$catTree->getCatItem($cat_id)->base);
    $tblpresentation->setPrLesson(null);
    $tblpresentation->setPrLesson($lesson);
    $tblpresentation->save();
    $tblpresentation->updateBlogCategoryEntryPath();

    if ($cat_id != $tblblogentry->getEntryCategory()) {
      $tblblogentry->setEntryCategory($cat_id);
      $tblblogentry->save();
    }

    foreach ($tblupdates as $tblupdate) {
      $done = $tblupdate->getUplDone();
      $correct = ($cat_id == $tblupdate->getUplCategory() && $lesson == $tblupdate->getUplLesson());
      $result = $correct? 1: 2;
      if ($done != $result) {
        if (!$done) $bonus = $correct? 5: -1;
        else $bonus = $correct? 6: -6;
        $us_id = $tblupdate->getUplUser();
        $tbluser = TbluserPeer::retrieveByPk($us_id);
        $tbluser->setUsScore($tbluser->getUsScore() + $bonus);
        $tbluser->save();
        userStatistics::incUserPoint($us_id, $bonus);

        $tblupdate->setUplDone($result);
        $tblupdate->save();
      }
    }
  }

  public function executeList() {
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->catItem = blogStore::$catTree->getCatItem($this->cat_id);
    $this->same = $this->getRequestParameter('same', $this->catItem->config['listtype']);
    if ($this->same != 'lesson' || !lessonList::allowTag($this->cat_id)) return parent::executeList();
    $this->cat_base = blogStore::$catTree->getCatItem($this->cat_id)->base;
    $this->lessons = @commonData::$lessons->getCatList($this->cat_base);
    if (!$this->lessons) $this->lessons = array(-1 => 'Ngoài chương trình SGK');

    $this->lessons = array(0 => 'Các '.$this->catItem->getCatTypeName().' chưa được sắp xếp') + $this->lessons;
    $this->groups = array_chunk($this->lessons, 6, true);
    $this->setTemplate('listlesson');
  }

  public function executeSamelesson() {
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->lesson = $this->getRequestParameter('lesson');
    $this->catItem = blogStore::$catTree->getCatItem($this->cat_id);
    if ($this->lesson) $this->title = commonData::$lessons->getTitle($this->catItem->base, $this->lesson);
    else $this->title = 'Các '.$this->catItem->getCatTypeName().' chưa được sắp xếp';

    $c = new Criteria();
    $c->add(TblblogentryPeer::ENTRY_CATEGORY, $this->cat_id);
    $c->add(TblblogentryPeer::ENTRY_LESSON, $this->lesson);
    $c->add(TblblogentryPeer::ENTRY_STATUS, 0);
    $c->addDescendingOrderByColumn(TblblogentryPeer::ENTRY_MODIFYDATE);

    $this->page = $this->getRequestParameter('page', 1);
    if ($entry_id = $this->getRequestParameter('entry_id')) {
      $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
      $c2 = new Criteria();
      $c2->add(TblblogentryPeer::ENTRY_CATEGORY, $this->cat_id);
      $c2->add(TblblogentryPeer::ENTRY_LESSON, $this->lesson);
      $c2->add(TblblogentryPeer::ENTRY_STATUS, 0);
      $c2->add(TblblogentryPeer::ENTRY_MODIFYDATE, $tblblogentry->getEntryModifydate(), Criteria::GREATER_THAN);
      $num = TblblogentryPeer::doCount($c2);
      $this->page = intval($num / $this->catItem->getDetailListItemCount()) + 1;
    }

    $this->pager = new PropelPager($c, 'TblblogentryPeer', 'doSelect', $this->page, $this->catItem->getDetailListItemCount());
  }

  public function executeRedirectnextuntag() {
    if ($entry_id = $this->getRequestParameter('entry_id')) {
      $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
      $this->forward404Unless($tblblogentry, 'Không tìm thấy tài liệu');
    } else {
      $blog_id = $this->getRequestParameter('blog_id');
      $cat_id = $this->getRequestParameter('cat_id');
      $pr_id = $this->getRequestParameter('pr_id');
      $c = new Criteria();
      $c->add(TblblogentryPeer::ENTRY_LINK, $pr_id);
      $c->add(TblblogentryPeer::ENTRY_TYPE, 0, Criteria::LESS_EQUAL);
      $c->add(TblblogentryPeer::ENTRY_STATUS, 2, Criteria::LESS_THAN);
      $c->add(TblblogentryPeer::ENTRY_BLOG, $blog_id);
      $tblblogentry = TblblogentryPeer::doSelectOne($c);
      $this->forward404Unless($tblblogentry, 'Không tìm thấy tài liệu');
      $tblblogentry->setEntryCategory($cat_id);
      $tblblogentry->setEntryLesson(null);
    }
    $next_id = $tblblogentry->getNextUntagId();
    $this->redirect('/present/show?entry_id='.($next_id? $next_id: $entry_id));
  }

  public function executeChangeblog() {
    $user_id = blogStore::$userId;
    $blog_id = $this->getRequestParameter('blog_id');
    $entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
    $next = $tblblogentry->getNextUntagId();
    $newLink = '';

    $cat_id = $tblblogentry->getEntryCategory();
    $newCatId = $this->getRequestParameter('cat_id');
    if (!$newCatId) {
      $base = TblblogcategoryPeer::retrieveByPk($cat_id)->getCatBase();
      $c = new Criteria();
      $c->add(TblblogcategoryPeer::CAT_BLOG, $blog_id);
      $c->add(TblblogcategoryPeer::CAT_BASE, $base);
      $tblcategory = TblblogcategoryPeer::doSelectOne($c);
      if ($tblcategory) $newCatId = $tblcategory->getCatId();
      else {$blog_id = 20; $newCatId = 7837896;}
    }

    $upb = TblupdateblogPeer::retrieveByPk($user_id, $entry_id);
    if ($upb == null) {
      $upb = new Tblupdateblog();
      $upb->setUpbUser($user_id);
      $upb->setUpbEntry($entry_id);
    }
    $upb->setUpbFromblog(blogStore::$blogId);
    $upb->setUpbFromcategory($cat_id);
    $upb->setUpbBlog($blog_id);
    $upb->setUpbCategory($newCatId);
    $upb->setUpbDate(date('Y-m-d H:i:s'));
    $upb->save();

    if ($tblblogentry->canEditEntry()) {
      $newLink = $this->updateEntryBlog($tblblogentry, $blog_id, $newCatId);
    } else {
      $c = new Criteria();
      $c->add(TblupdateblogPeer::UPB_ENTRY, $entry_id);
      $tblupdates = TblupdateblogPeer::doSelect($c);
      $total = count($tblupdates);

      if ($total >= sfConfig::get('sf_max_lesson_tagging')) {
        $same = 0;
        foreach ($tblupdates as $tblupdate) {
          if ($blog_id == $tblupdate->getUpbBlog()) $same++;
        }
        if ($same / $total * 100 > sfConfig::get('sf_lesson_tagging_percent')) {
          $tblblogentry->setEntryType($blog_id == 21? -1: -2);
          $tblblogentry->setEntryCategory($newCatId);
          $tblblogentry->setEntryBlog($blog_id);
          $tblblogentry->save();
          $newLink = $this->updateEntryBlog($tblblogentry, $blog_id, $newCatId);
        }
      }
    }

    $nextLink = ($next? ' Xem <a href="/present/show/entry_id/'.$next.'">bài tiếp theo...</a>': '');
    return $this->renderText('<center>Cảm ơn đã xác nhận.'.$newLink.$nextLink.'</center>');
  }

  private function updateEntryBlog($tblblogentry, $blog_id, $newCatId) {
    $tblblogentry->setEntryType($blog_id == 21? -1: -2);
    $tblblogentry->setEntryCategory($newCatId);
    $tblblogentry->setEntryBlog($blog_id);
    $tblblogentry->save();
    return ' Đường dẫn mới <a href="/entry/showglobal?entry_id='.$tblblogentry->getEntryId().'" target="_blank">tại đây</a>.';
  }

  public function executeUpdatefolder() {
    $user_id = blogStore::$userId;
    $entry_id = $this->getRequestParameter('entry_id');
    $tblblogentry = TblblogentryPeer::retrieveByPk($entry_id);
    $this->forward404Unless($tblblogentry, 'Tài liệu không tồn tại');
    $this->forward404If($tblblogentry->getEntryLesson() > 0, 'Tài liệu đã được tag tên bài');
    $this->forwardUnless($tblblogentry->canMod(), 'default', 'secure');

    $next = $tblblogentry->getNextUntagId();
    $cat_id = $tblblogentry->getEntryCategory();
    $newCatId = $this->getRequestParameter('cat_id');
    $catItem = blogStore::$catTree->getCatItem($newCatId);

    $upb = TblupdateblogPeer::retrieveByPk($user_id, $entry_id);
    if ($upb == null) {
      $upb = new Tblupdateblog();
      $upb->setUpbUser($user_id);
      $upb->setUpbEntry($entry_id);
      $upb->setUpbFromcategory($cat_id);
      $upb->setUpbFromblog(blogStore::$blogId);
    }
    $upb->setUpbCategory($newCatId);
    $upb->setUpbDate(date('Y-m-d H:i:s'));
    $upb->save();

    $tblpresentation = $tblblogentry->getTblpresentation();
    $tblpresentation->setPrCategory($catItem->base);
    $tblpresentation->save();
    $tblblogentry->setEntryCategory($newCatId);
    $tblblogentry->save();

    $nextLink = ($next? ' Xem <a href="/present/show/entry_id/'.$next.'">bài tiếp theo...</a>': '');
    return $this->renderText('<center>Đã chuyển sang thư mục <b>'.$catItem->name.'</b>.'.$nextLink.'</center>');
  }

  public function executeConfirm() {
    $this->title = urldecode($this->getRequestParameter('title'));
    $this->cat_id = $this->getRequestParameter('cat_id');
    $this->cat_base = blogStore::$catTree->getCatItem($this->cat_id)->base;
    $this->subject = commonData::$baseCatTree->getCatItem($this->cat_base)->name;
  }
}
