<?php

/**
 * admin actions.
 *
 * @package    tvtl
 * @subpackage admin
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class adminActions extends sfMyActions
{
  /**
   * Executes index action
   *
   */
  public function executeIndex() {
    $this->title = blogStore::$blog->getBlTitle();
    $this->copyright = blogStore::getParam('config/copyright');
    $this->repeat_bkgnd = blogStore::getParam('config/background/repeat') !== 'no-repeat';
    $this->fixed_bkgnd = blogStore::getParam('config/background/fixed');
    $this->screenwidth = blogStore::getParam('config/screenwidth', 'normal');
    $this->modulepos = blogStore::getParam('config/leftmenu', 'left');
    $this->currentTheme = blogStore::getParam('layout', 'standard');
  }

  /**
   * update interface basic
   *
   */
  public function executeUpdatebasic() {
    $moduleConfig = &blogStore::$moduleConfig;
    $path = blogStore::getBlogFolder().'/layout/';

    if (!$this->getRequest()->hasErrors() && $this->getRequest()->hasFiles()) {
      foreach ($this->getRequest()->getFileNames() as $file) {
        $fileType = $this->getRequest()->getFileType($file);
        $isFlash = in_array($fileType, array('application/x-shockwave-flash'));
        $isImage = in_array($fileType, array('image/png', 'image/jpeg', 'image/gif', 'image/pjpeg'));
        if ($isFlash || $isImage) {
          $fileName = $this->getRequest()->getFileName($file);
          $fileName = myUtility::getSafeFileName($fileName);
          if ($file == 'background' && $isImage) {
            $moduleConfig['config']['background']['url'] = $fileName;
          }
          if ($file == 'banner') {
            list($width, $height) = sfConversion::getImageSize($path.$fileName);
            $moduleConfig['config']['banner'] = array('width'=>$width, 'height'=>$height);
            $moduleConfig['config']['banner'] = array('width'=>$width, 'height'=>$height);
            $moduleConfig['config']['banner'][$isFlash? 'swfurl': 'url'] = $fileName;
          }
          $this->getRequest()->moveFile($file, $path.$fileName);
          myUtility::track_upload($path.$fileName, 'blogs');
        }
      }
    }
    if ($this->getRequestParameter('no_bkgnd')) {
      unset($moduleConfig['config']['background']);
    } else {
      $moduleConfig['config']['background']['repeat'] = $this->getRequestParameter('repeat_bkgnd', 'no-repeat');
      $moduleConfig['config']['background']['fixed'] = $this->getRequestParameter('fixed_bkgnd', 'false');
    }
    $moduleConfig['config']['copyright'] = $this->getRequestParameter('copyright');
    $moduleConfig['config']['screenwidth'] = $this->getRequestParameter('screenwidth');
    $moduleConfig['config']['leftmenu'] = $this->getRequestParameter('modulepos');

    $tblblog = TblblogPeer::retrieveByPK(blogStore::$blogId);
    $tblblog->setBlModuleConfig(sfYaml::dump($moduleConfig));
    $tblblog->setBlTitle($this->getRequestParameter('title'));
    $tblblog->save();
    blogStore::resetCache();
    $this->redirect('admin/index');
  }

  public function executeModule() {
    $typeBlog = blogStore::getParam('config/type', 'all');
    $this->defModules = sfConfig::get('mod_admin_standard_config');
    $this->defModules = $this->defModules[$typeBlog]['modules'];
    $this->modules = blogStore::$moduleConfig['modules'];
    $this->position = array();
    $p = 1;
    foreach ($this->modules as $key => &$module) {
      if (array_key_exists($key, $this->defModules)) unset($this->defModules[$key]);
      $module['order'] = $this->position[$module['pos']][$p] = $p;
      $p++;
    }
    $this->config_links = sfConfig::get('mod_admin_link_to_config');
    $this->modulepos = blogStore::getParam('config/leftmenu', 'left');
  }

  /**
   * Enter description here...
   *
   */
  public function executeUpdateadvance() {
    $modules = &blogStore::$moduleConfig['modules'];
    $action = $this->getRequestParameter('act');
    $name = $this->getRequestParameter('name');
    if ($action=='column') {
      $modulepos = $this->getRequestParameter('modulepos');
      $modules[$name]['pos'] = $modulepos;
    }
    if ($action=='order') {
      $pos = $this->getRequestParameter('order') - 1;
      $module = $modules[$name];
      unset($modules[$name]);
      $modules = array_slice($modules, 0, $pos) + array($name=>$module) + array_slice($modules, $pos);
    }
    if ($action=='status') {
      $status = $this->getRequestParameter('status');
      $modules[$name]['visible'] = $status;
    }
    if ($action=='activate') {
      $typeBlog = blogStore::getParam('config/type', 'all');
      $moduleConfigDefault = sfConfig::get('mod_admin_standard_config');
      $moduleConfigDefault = $moduleConfigDefault[$typeBlog];
      $modules[$name] = $moduleConfigDefault['modules'][$name];
    }
    $this->updateConfig('module');
  }

  /**
   * update module config and refresh page
   *
   */
  private function updateConfig($page = '') {
    $configData = sfYaml::dump(blogStore::$moduleConfig);
    $this->forward404If(strlen($configData) > 64000, 'Mã nhúng quá dài hoặc có quá nhiều mã nhúng');
    $tblblog = TblblogPeer::retrieveByPK(blogStore::$blogId);
    $tblblog->setBlModuleConfig($configData);
    $tblblog->save();
    blogStore::resetCache();
    if ($page != '') $this->redirect('admin/'.$page);
  }

 /**
  * author:manhtl
  *
  */
  public function executeUpdatemoduletitle() {
    $name = $this->getRequestParameter('name');
    $title = $this->getRequestParameter('title', $name);
    blogStore::$moduleConfig['modules'][$name]['name'] = $title;
    $this->updateConfig();
    return $this->renderText($title);
 }

 /**
  * Enter description here...
  *
  */
 public function executeSearchmember() {
   $search = $this->getRequestParameter('search');
   $url = 'admin/listmember?search='.$search;
   $keysearch = $this->getRequestParameter('keysearch');
   if($keysearch == 'Tìm kiếm...') {
     $keysearch = '';
   }
   if($keysearch != '') {
     $url .= '&keysearch='.base64_encode($keysearch);
   }
   $namesearch = $this->getRequestParameter('namesearch');
   if($namesearch != '') {
     $url .= '&namesearch='.$namesearch;
   }
    //echo $url;exit;
   $this->redirect($url);
 }

 /**
  * Enter description here...
  *
  */
 public function executeListmember() {
   $c = new Criteria();
   //display sign increase or decrease
   $this->mailSign = null;
   $this->fullnameSign = null;
   $this->nicknameSign = null;
   $this->dateSign = null;
   $down = '<font size="3">↓</font>';
   $up = '<font size="3">↑</font>';
   //init status
   $this->sFullname = true;
   $this->sEmail = false;
   $this->sNickname = false;
   $this->keysearch = null;
   $this->keysearchlink = null;
   $this->linkOrder = null;
   $search = $this->getRequestParameter('search');
   if($search == 1) {
     $this->keysearch =  base64_decode($this->getRequestParameter('keysearch'));
     $this->namesearch = $this->getRequestParameter('namesearch');
     switch($this->namesearch) {
       case 'fullname':
         $c->add(TblbloguserPeer::US_FULLNAME,'%'.$this->keysearch.'%',Criteria::LIKE);
         break;
       case 'nickname':
         $c->add(TblbloguserPeer::US_NICKNAME,'%'.$this->keysearch.'%',Criteria::LIKE);
         $this->sNickname = true;
         $this->sFullname = false;
         break;
       case 'email':
         $c->add(TblbloguserPeer::US_EMAIL,'%'.$this->keysearch.'%',Criteria::LIKE);
         $this->sEmail = true;
         $this->sFullname = false;
         break;
     }
   }

   //order by fullname
   $this->fullname = $this->getRequestParameter('fullname');
   if($this->fullname != null) {
     $this->linkOrder = '&fullname='.$this->fullname;
     $this->fullname = ($this->fullname == 1)?0:1;
     if($this->fullname == 0) {
        $c->addAscendingOrderByColumn(TblbloguserPeer::US_FULLNAME );
        $this->fullnameSign = $up;
     } else {
       $c->addDescendingOrderByColumn(TblbloguserPeer::US_FULLNAME);
       $this->fullnameSign = $down;
     }
   } else {
     $this->fullname = 0;
   }

   //order by nickname
   $this->nickname = $this->getRequestParameter('nickname');
   if($this->nickname != null) {
     $this->linkOrder = '&nickname='.$this->nickname;
     $this->nickname = ($this->nickname == 1)?0:1;
     if($this->nickname == 0) {
        $c->addAscendingOrderByColumn(TblbloguserPeer::US_NICKNAME);
        $this->nicknameSign = $up;
     } else {
       $c->addDescendingOrderByColumn(TblbloguserPeer::US_NICKNAME);
       $this->nicknameSign = $down;
     }
   } else {
     $this->nickname = 0;
   }

   //order by email
   $this->email = $this->getRequestParameter('email');
   if($this->email != null) {
     $this->linkOrder = '&email='.$this->email;
     $this->email = ($this->email == 1)?0:1;
     if($this->email == 0) {
       $c->addAscendingOrderByColumn(TblbloguserPeer::US_EMAIL);
       $this->mailSign = $up;
     } else {
       $c->addDescendingOrderByColumn(TblbloguserPeer::US_EMAIL);
       $this->mailSign = $down;
     }
   } else {
     $this->email = 0;
   }

   //order by joindate
   $this->joindate = $this->getRequestParameter('joindate');
   if($this->joindate != null) {
     $this->linkOrder = '&joindate='.$this->joindate;
     $this->joindate = ($this->joindate == 1)?0:1;
     if($this->joindate == 0) {
       $c->addAscendingOrderByColumn(TblbloguserPeer::US_JOINDATE);
        $this->dateSign = $up;
     } else {
       $c->addDescendingOrderByColumn(TblbloguserPeer::US_JOINDATE);
       $this->dateSign = $down;
     }
   } else {
     $this->joindate = 0;
   }

   $c->add(TblbloguserPeer::US_BLOG,blogStore::$blogId);
   //$c->addJoin(TblbloguserPeer::US_USER,TbluserPeer::US_ID);
   $this->page = $this->getRequestParameter('page',1);
   $this->pager = new PropelPager($c,'TblbloguserPeer','doSelect',$this->page,20);
   if($this->keysearch != '') {
    $this->keysearchlink = '&search=1&namesearch='.$this->namesearch.'&keysearch='.$this->keysearch;
   }
   //get all category
   $this->cats = array();
   $c = new Criteria();
   $c->add(TblblogcategoryPeer::CAT_BLOG,blogStore::$blogId);
   $tblblogcategory = TblblogcategoryPeer::doSelect($c);
   foreach($tblblogcategory as $cat) {
     $this->cats[$cat->getCatId()] = $cat->getCatName();
   }

 }

 /**
  * Enter description here...
  *
  */
 public function executeDelmember() {
   $user_id = $this->getRequestParameter('user');
   foreach($user_id as $id) {
      $tblbloguser = TblbloguserPeer::retrieveByPK(blogStore::$blogId,$id);
      $tblbloguser->delete();
   }
   $this->redirect($this->getRequest()->getReferer());
 }

 /**
  * Change rights sent entry of member...
  *
  */
 public function executeEditmember() {
   $cat_ids = $this->getRequestParameter('cat_id');
   if($cat_ids == null) {
     $user_id = $this->getRequestParameter('id');
     $c = new Criteria();
     $c->add(TblbloguserPeer::US_USER,$user_id);
     $c->add(TblbloguserPeer::US_BLOG,blogStore::$blogId);
     $tblbloguser = TblbloguserPeer::doSelectJoinTbluser($c);
     $this->forward404Unless($tblbloguser,'Thành viên này đã bị xóa');
     $this->cat_exist = $tblbloguser[0]->getUsCategories();
     $this->fullname = $tblbloguser[0]->getTbluser()->getUsFullname();
     $this->user_id = $user_id;
   } else {
     $user_id = $this->getRequestParameter('user_id');
     $tblbloguser = TblbloguserPeer::retrieveByPK(blogStore::$blogId,$user_id);
     $tblbloguser->setUsCategories($cat_ids);
     $tblbloguser->setUsLastvisit(date("Y-m-d H:i:s"));
     $tblbloguser->save();
     return $this->renderText('Bạn đã cập nhật thành công');
   }
 }

  /**
   * Enter description here...
   *
   */
  public function executeAcceptmember() {
    $user_id = $this->getRequestParameter('uid');
    $tblbloguser = TblbloguserPeer::retrieveByPK(blogStore::$blogId, $user_id);
    $tblbloguser->setUsRole(1);
    $tblbloguser->save();
    $this->redirect($this->getRequest()->getReferer());
  }

  /**
   * manage folder
   */
  public function executeManagefolder() {
   $cat_ids = $this->getRequestParameter('cat_id');
   if($cat_ids == null) {
     $user_id = $this->getRequestParameter('id');
     $c = new Criteria();
     $c->add(TblbloguserPeer::US_USER,$user_id);
     $c->add(TblbloguserPeer::US_BLOG,blogStore::$blogId);
     $tblbloguser = TblbloguserPeer::doSelectJoinTbluser($c);
     $this->forward404Unless($tblbloguser,'Thành viên này đã bị xóa');
     $this->cat_exist = $tblbloguser[0]->getUsManagecat();
     $this->fullname = $tblbloguser[0]->getTbluser()->getUsFullname();
     $this->user_id = $user_id;
   } else {
     $user_id = $this->getRequestParameter('user_id');
     $tblbloguser = TblbloguserPeer::retrieveByPK(blogStore::$blogId,$user_id);
     $tblbloguser->setUsManagecat($cat_ids);
     $tblbloguser->setUsLastvisit(date("Y-m-d H:i:s"));
     $tblbloguser->save();
     return $this->renderText('Bạn đã cập nhật thành công');
   }
  }

 /**
  * Enter description here...
  *
  */
 public function executeListfolder() {
   $this->cat = $this->getRequestParameter('cat');
   $this->error_msg = $this->getRequestParameter('error', 0);
   if($this->cat == null || $this->cat == -1) {
     $this->cat = 'root';
   } else {
     $this->cat = 'tr'.$this->cat;
   }
   $this->filter = null;
 }

 /**
  * Enter description here...
  *
  */
 public function executeUpdatefolder() {
   $catId = $this->getRequestParameter('listCat');
   if (preg_match('/[0-9]+/', $catId, $catId)) $catId = intval($catId[0]);
   $tblblogcategory = TblblogcategoryPeer::retrieveByPK($catId);
   $catParent = $tblblogcategory->getCatParent();
   $orderCurrent = $tblblogcategory->getCatOrder();

   $c = new Criteria();
   $c->add(TblblogcategoryPeer::CAT_PARENT,$catParent);
   $c->add(TblblogcategoryPeer::CAT_BLOG ,blogStore::$blogId);
   $c->addAscendingOrderByColumn(TblblogcategoryPeer::CAT_ORDER);

   $act = $this->getRequestParameter('act');

   $tblcategories = TblblogcategoryPeer::doSelect($c);
   $down = false;
   //lam the nay de update lai cac order = 0
   foreach ($tblcategories as $key => $tblcategory) {
      $order = $key+1;
      if ($down == true) {
        $down = false;
        continue;
      }
      if ($tblcategory->getCatId() == $catId) {
        switch ($act) {
          case 'up':
            if ($key > 0) {
              $tblcategories[$key]->setCatOrder($order-1);
              $tblcategories[$key]->save();
              $tblcategories[$key-1]->setCatOrder($order);
              $tblcategories[$key-1]->save();
            }
            break;
          case 'down':
            if ($key+1 < count($tblcategories)) {
              $tblcategories[$key]->setCatOrder($order+1);
              $tblcategories[$key]->save();
              $tblcategories[$key+1]->setCatOrder($order);
              $tblcategories[$key+1]->save();
              $down = true;
            }
            break;
        }
      } else {
        $tblcategory->setCatOrder($order);
        $tblcategory->save();
      }
   }

   $this->resetCategoryCache();
   $this->redirect('admin/listfolder?cat='.$catParent);
 }


  public function executeMoveright() {
    $catId = $this->getRequestParameter('listCat');
    if (preg_match('/[0-9]+/', $catId, $catId)) $catId = $catId[0];
    $tblblogcategory = TblblogcategoryPeer::retrieveByPK($catId);
    $order = $tblblogcategory->getCatOrder();
    $catParent = $tblblogcategory->getCatParent();
    if (!$this->canChangeCat()) {
      $this->redirect('admin/listfolder?cat='.$catParent.'&error=1');
    }
    if ($order > 1) {
      //get cat before cat current
      $c = new Criteria();
      $c->add(TblblogcategoryPeer::CAT_BLOG, blogStore::$blogId);
      $c->add(TblblogcategoryPeer::CAT_ORDER, $order, Criteria::LESS_THAN);
      $c->add(TblblogcategoryPeer::CAT_PARENT, $catParent);
      $c->addDescendingOrderByColumn(TblblogcategoryPeer::CAT_ORDER);
      $tblcatbefore = TblblogcategoryPeer::doSelectOne($c);
      $beforeType = $tblcatbefore->getCatType();
      $beforeId = $tblcatbefore->getCatId();
      $beforePath = $tblcatbefore->getCatPath();
      if ($beforeType != $tblblogcategory->getCatType()) {
        $this->redirect('admin/listfolder?cat='.$catParent.'&error=2');
      }

      //get max element in catbefore
      $c = new Criteria();
      $c->add(TblblogcategoryPeer::CAT_BLOG, blogStore::$blogId);
      $c->add(TblblogcategoryPeer::CAT_PARENT, $beforeId);
      $c->addDescendingOrderByColumn(TblblogcategoryPeer::CAT_ORDER);
      $tbllastcat = TblblogcategoryPeer::doSelectOne($c);
      $maxOrder = $tbllastcat? $tbllastcat->getCatOrder(): 0;

      //update catpath for all sub categories
      $catPath = $tblblogcategory->getCatPath();
      $newPath = $beforePath.','.$catId;
      $this->changeCatPath($catId, $catPath, $newPath);

      //update category
      $tblblogcategory->setCatOrder($maxOrder + 1);
      $tblblogcategory->setCatParent($beforeId);
      $tblblogcategory->setCatPath($newPath);
      $tblblogcategory->save();

      $this->changeCatOrder($tblcatbefore, -1);
      $this->changeCatEntry($beforeId, $catId, 'insert');
      $this->resetCategoryCache();
    } else {
      $this->redirect('admin/listfolder?cat='.$catParent.'&error=3');
    }
    $this->redirect('admin/listfolder?cat='.$beforeId);
  }

  public function executeMoveleft() {
    $catId = $this->getRequestParameter('listCat');
    if (preg_match('/[0-9]+/', $catId, $catId)) $catId = $catId[0];
    $tblblogcategory = TblblogcategoryPeer::retrieveByPK($catId);
    $catParent = $tblblogcategory->getCatParent();
    if (!$this->canChangeCat()) {
      $this->redirect('admin/listfolder?cat='.$catParent.'&error=1');
    }
    if ($catParent != -1) {
      $this->changeCatOrder($tblblogcategory, -1);
      $tblparent = TblblogcategoryPeer::retrieveByPK($catParent);
      $order = $tblparent->getCatOrder() + 1;

      $catPath = $tblblogcategory->getCatPath();
      $paths = explode(',', $catPath);
      unset($paths[count($paths) - 2]);
      $newPath = implode(',', $paths);
      $this->changeCatPath($catId, $catPath, $newPath);

      $len = count($paths);
      $parent = ($len < 2)? -1: $paths[$len - 2];
      $tblblogcategory->setCatParent($parent);
      $tblblogcategory->setCatOrder($order);
      $tblblogcategory->setCatPath($newPath);
      $tblblogcategory->save();

      $this->changeCatOrder($tblblogcategory, 1);
      $this->changeCatEntry($catParent, $catId, 'delete');
      $this->resetCategoryCache();
    }
    $this->redirect('admin/listfolder?cat='.$catParent);
  }

  private function canChangeCat() {
    $cache = blogStore::getCache();
    $cacheName = 'changingCategory.'.blogStore::$blogId;
    if ($cache->getWithQueue($cacheName, '')) return false;
    $cache->set($cacheName, '', 1, 30);
    return true;
  }

  private function changeCatOrder($tblblogcategory, $unit) {
    $id = $tblblogcategory->getCatId();
    $order = $tblblogcategory->getCatOrder();
    $parent = $tblblogcategory->getCatParent();
    $c = new Criteria();
    $c->add(TblblogcategoryPeer::CAT_BLOG, blogStore::$blogId);
    $c->add(TblblogcategoryPeer::CAT_ID, $id, Criteria::NOT_EQUAL);
    $c->add(TblblogcategoryPeer::CAT_PARENT, $parent, Criteria::EQUAL);
    $c->add(TblblogcategoryPeer::CAT_ORDER, $order, Criteria::GREATER_EQUAL);
    $tblcategory = TblblogcategoryPeer::doSelect($c);
    foreach ($tblcategory as $category) {
      $category->setCatOrder($category->getCatOrder() + $unit);
      $category->save();
    }
  }

  private function changeCatPath($id, $oldPath, $newPath) {
    $c = new Criteria();
    $c->add(TblblogcategoryPeer::CAT_ID, $id, Criteria::NOT_EQUAL);
    $c->add(TblblogcategoryPeer::CAT_BLOG, blogStore::$blogId, Criteria::EQUAL);
    $c->add(TblblogcategoryPeer::CAT_PATH, $oldPath.',%', Criteria::LIKE);
    $tblcategory = TblblogcategoryPeer::doSelect($c);
    foreach ($tblcategory as $category) {
      $category->setCatPath(str_replace($oldPath, $newPath, $category->getCatPath()));
      $category->save();
    }
  }

  private function changeCatEntry($parentId, $catId, $action) {
    $c = new Criteria();
    $c->add(TblblogcategoryentryPeer::CE_CATEGORY, $catId);
    $tblcategoryentry = TblblogcategoryentryPeer::doSelect($c);
    if ($action == 'insert') { //for move right
      foreach ($tblcategoryentry as $ce) {
        $insert = $ce->copy();
        $insert->setCeCategory($parentId);
        $insert->save();
      }
    }
    if ($action == 'delete') { //for move left
      $ce_array = array();
      foreach ($tblcategoryentry as $ce) {
        $ce_array[] = $ce->getCeEntry();
      }
      $c = new Criteria();
      $c->add(TblblogcategoryentryPeer::CE_CATEGORY, $parentId);
      $c->add(TblblogcategoryentryPeer::CE_ENTRY, $ce_array, Criteria::IN);
      TblblogcategoryentryPeer::doDelete($c);
    }
  }

 /**
  * Create new folder
  * Get request from listfolder action (javascript)
  *
  * @return unknown
  */
  public function executeCreatefolder() {
    $parentId = $this->getRequestParameter('id');
    if ($parentId=='root') {
      $parentId = -1;
    } else {
      if (!preg_match('/[0-9]+/', $parentId, $parentId)) return sfView::NONE;
      $parentId = $parentId[0];
    }
    $catName = $this->getRequestParameter('name');
    $catType = $this->getRequestParameter('type');
    $catBase = $this->getRequestParameter('base');
    $public = $this->getRequestParameter('public');
    if ($catName=='' || $catType=='') return sfView::NONE;
    if (2==$catType) $catBase = 0; else if ($catBase=='') return sfView::NONE;

    if ($parentId!=-1) {
      $tblparentCategory = TblblogcategoryPeer::retrieveByPK($parentId);
      if (!$tblparentCategory) return sfView::NONE;
    }
    $c = new Criteria();
    $c->add(TblblogcategoryPeer::CAT_PARENT, $parentId);
    $c->add(TblblogcategoryPeer::CAT_BLOG, blogStore::$blogId);
    $c->addDescendingOrderByColumn(TblblogcategoryPeer::CAT_ORDER);
    $lastCat = TblblogcategoryPeer::doSelectOne($c);
    try {
      $tblblogcategory = new Tblblogcategory();
      $tblblogcategory->setCatBlog(blogStore::$blogId);
      $tblblogcategory->setCatName($catName);
      $tblblogcategory->setCatParent($parentId);
      $tblblogcategory->setCatType($catType);
      if ($lastCat)
        $tblblogcategory->setCatOrder($lastCat->getCatOrder()+1);
      else
        $tblblogcategory->setCatOrder(0);
      $tblblogcategory->setCatPath('');
      $tblblogcategory->setCatConfig('');
      $tblblogcategory->setCatBase($catBase);
      $tblblogcategory->setCatPublic($public);
      if ($public == -1) {
        $config = sfYaml::load($tblblogcategory->getCatConfig());
        $config['listtype'] = 'category';
        $tblblogcategory->setCatConfig(sfYaml::dump($config));
      }
      $tblblogcategory->save();
      $this->resetCategoryCache();
      return $this->renderText('OK:'.$tblblogcategory->getCatId());
    } catch (Exception $e) {
      return sfView::NONE;
    }
  }

  /**
   * Delete folder if it's empty (no child, no entry)
   *
   * @return unknown
   */
  public function executeDeletefolder() {
    $id = $this->getRequestParameter('id');
    if ($id=='') return sfView::NONE;

    if (preg_match('/[0-9]+/', $id, $id)) $id = $id[0];
    $tblblogcategory = TblblogcategoryPeer::retrieveByPK($id);
    if (!$tblblogcategory) return sfView::NONE;

    // Count number of child category
    $c = new Criteria();
    $c->add(TblblogcategoryPeer::CAT_BLOG, blogStore::$blogId);
    $c->add(TblblogcategoryPeer::CAT_PARENT, $tblblogcategory->getCatId());
    $numChildCat = TblblogcategoryPeer::doCount($c);

    if ($numChildCat>0) {
      return $this->renderText('Thu muc van con thu muc con. Khong the xoa!');
    }

    // Count number of entry
    $c = new Criteria();
    $c->add(TblblogcategoryentryPeer::CE_CATEGORY, $tblblogcategory->getCatId());
    $c->add(TblblogcategoryentryPeer::CE_STATUS, 0);
    $numChildEntry = TblblogcategoryentryPeer::doCount($c);

    if ($numChildEntry>0) {
      return $this->renderText('Thu muc van chua cac bai viet, bai giang. Khong the xoa!');
    }

    // Delete category entry
    $c = new Criteria();
    $c->add(TblblogcategoryentryPeer::CE_CATEGORY, $tblblogcategory->getCatId());
    TblblogcategoryentryPeer::doDelete($c);

    // Set all entry to Recycle
    $c = new Criteria();
    $c->add(TblblogentryPeer::ENTRY_CATEGORY, $tblblogcategory->getCatId());
    $v = new Criteria();
    $v->add(TblblogentryPeer::ENTRY_CATEGORY, 0);
    BasePeer::doUpdate($c, $v, Propel::getConnection(TblblogentryPeer::DATABASE_NAME));

    // Delete category
    $tblblogcategory->delete();
    $this->resetCategoryCache();
    return $this->renderText('OK');
  }

  /**
   * Rename category
   *
   * @return unknown
   */
  public function executeRenamefolder() {
    $id = $this->getRequestParameter('id');
    $name = $this->getRequestParameter('name');
    $base = $this->getRequestParameter('base');
    $public = $this->getRequestParameter('public');

    if ($id=='' || $name=='') return sfView::NONE;

    if (preg_match('/[0-9]+/', $id, $id)) $id = $id[0];
    $tblblogcategory = TblblogcategoryPeer::retrieveByPK($id);
    if (!$tblblogcategory) return sfView::NONE;

    if ($tblblogcategory->getCatType()==2) $base = 0;
      else if ($base=='') return sfView::NONE;

    try {
      $tblblogcategory->setCatName($name);
      $tblblogcategory->setCatBase($base);
      $tblblogcategory->setCatPublic($public);
      $config = sfYaml::load($tblblogcategory->getCatConfig());
      $config['listtype'] = $this->getRequestParameter('multiple', 'all');
      $config['list'] = $this->getRequestParameter('list', 'thumb');
      $tblblogcategory->setCatConfig(sfYaml::dump($config));
      $tblblogcategory->save();
      $this->resetCategoryCache();
      return $this->renderText('OK');
    } catch (Exception $e) {
      return sfView::NONE;
    }
  }

  /**
   * Change public of category
   */
  public function executeChangepublic() {
    $id = $this->getRequestParameter('id');
    $catPublic = $this->getRequestParameter('catPublic');
    if ($id=='') return sfView::NONE;
    if (preg_match('/[0-9]+/', $id, $id)) $id = $id[0];
    $tblblogcategory = TblblogcategoryPeer::retrieveByPK($id);
    $tblblogcategory->setCatPublic($catPublic);
    $tblblogcategory->save();
    $this->resetCategoryCache();
    return $this->renderText('OK');
  }

  /**
   * Reset cache when categories are modified
   *
   */
  public function resetCategoryCache() {
    @unlink(blogStore::getJcatFileName());

    $tblblog = TblblogPeer::retrieveByPK(blogStore::$blogId);
    $tblblog->setBlLastupdate(date('Y-m-d H:i:s'));
    $tblblog->save();

    blogStore::resetCache();
  }
  
  /**
   * Function permit admin blog
   * create poll for his blog
   *
   */

  public function executeListpoll() {
    $c = new Criteria();
    $c->add(TblblogpollPeer::POLL_BLOG,blogStore::$blogId);
    $c->addDescendingOrderByColumn(TblblogpollPeer::POLL_CREATEDATE);
    $this->page = $this->getRequestParameter('page', 1);
    $this->pager = new PropelPager($c, 'TblblogpollPeer', 'doSelect', $this->page, 5);

    $this->results = array();
    foreach($this->pager->getResult() as $poll) {
      $pid = $poll->getPollId();
      $answers = split('\|', $poll->getPollQuestions());
      $this->results[$pid]['total'] = 0;
      foreach ($answers as $key => $answer) {
        $c = new Criteria();
        $c->add(TblblogpolldataPeer::PD_CHOICE, $key);
        $c->add(TblblogpolldataPeer::PD_POLL, $pid);
        $quantity = TblblogpolldataPeer::doCount($c);
        $this->results[$pid]['answer'][$key] = $quantity;
        $this->results[$pid]['total'] += $quantity;
      }
    }
  }

  public function executeEditpoll() {
    $this->page = $this->getRequestParameter('page', 1);
    $this->editId = $this->getRequestParameter('id', 0);
    $this->active = 1;
    $tblblogpoll = TblblogpollPeer::retrieveByPK($this->editId);
    if ($tblblogpoll) {
      $this->question = $tblblogpoll->getPollName();
      $this->answers = split('\|',$tblblogpoll->getPollQuestions());
      $this->active = $tblblogpoll->getPollActive();
    }
  }

  public function executeUpdatepoll() {
    //create or update poll data
    $editId = $this->getRequestParameter('editId', 0);
    if ($editId != null) {
      $tblblogpoll = TblblogpollPeer::retrieveByPK($editId);
      $question = $this->getRequestParameter('question', '');
      $type = $this->getRequestParameter('multianswer', 1);
      $answers = $this->getRequestParameter('answer');
      foreach($answers as $key => $answer) {
        if ($answer == '') unset($answers[$key]);
      }
      $answer_str = implode('|',$answers);

      //set active poll and unactive others
      $active = $this->getRequestParameter('active');
      if ($active == 1) {
        $c = new Criteria();
        $c->add(TblblogpollPeer::POLL_BLOG, blogStore::$blogId);
        $c->add(TblblogpollPeer::POLL_ACTIVE, 1);
        if ($editId != 0) $c->add(TblblogpollPeer::POLL_ID, $editId, Criteria::NOT_EQUAL);
        $tblpoll = TblblogpollPeer::doSelect($c);
        foreach($tblpoll as $poll) {
          $poll->setPollActive(0);
          $poll->save();
        }
      }

      //insert into db
      if (!$tblblogpoll) {//if create a new poll
        $tblblogpoll = new Tblblogpoll();
        $tblblogpoll->setPollBlog(blogStore::$blogId);
        $tblblogpoll->setPollCreatedate(date("Y-m-d H:i:s"));
      }
      $tblblogpoll->setPollName($question);
      $tblblogpoll->setPollQuestions($answer_str);
      $tblblogpoll->setPollType($type);
      $tblblogpoll->setPollActive($active);
      $tblblogpoll->save();
    }

    //delete poll
    $poll = $this->getRequestParameter('poll');
    if ($poll != null) {
      foreach (explode('|', $poll) as $delPoll) {
        $tblblogpoll = TblblogpollPeer::retrieveByPK($delPoll);
        $tblblogpoll->delete();
      }
    }
    //change status
    $actId = $this->getRequestParameter('actId');
    if ($actId != null) {
      $c = new Criteria();
      $c->add(TblblogpollPeer::POLL_BLOG,blogStore::$blogId);
      $c->add(TblblogpollPeer::POLL_ACTIVE, 1);
      $tblpoll = TblblogpollPeer::doSelect($c);
      foreach($tblpoll as $poll) {
        $poll->setPollActive(0);
        $poll->save();
      }
      $tblblogpoll = TblblogpollPeer::retrieveByPK($actId);
      $tblblogpoll->setPollActive(1);
      $tblblogpoll->save();
    }
    blogStore::resetCache();
    $this->forward('admin', 'listpoll');
  }

  /**
   * Reset cache of each blog
   */
  public function executeResetcache() {
    $this->blogName = $this->getRequestParameter('name', blogStore::$blogName);
    if (blogStore::$blogName=='main' || $this->blogName==blogStore::$blogName) {
      // Only main blog can reset cache of other blog
      $cache = blogStore::getCache();
      //$cache->clean($this->blogName, 'all');
      blogStore::resetCache();
    }
    $this->redirect('/');
  }
  /**
   * Disable blog
   */
  public function executeChangestatus() {
    $blogId = $this->getRequestParameter('blogId');
    $tblblog = TblblogPeer::retrieveByPK($blogId);
    $value = $tblblog->getBlActive();
    if($value == 0) $value = 1;
    else $value = 0;
    $tblblog->setBlActive($value);
    $tblblog->save();
    $this->redirect('/');
  }
  /**
   * Delete blog
   *
   */
  public function executeDelete() {
    if (!blogStore::isAdministator()) $this->redirect('/');
    $blogStatus = $this->getRequestParameter('blogStatus');
    if ($blogStatus && $blogStatus < 0) {
      $c = new Criteria();
      $c->add(TblblogPeer::BL_ACTIVE, $blogStatus);
      $tblblogs = TblblogPeer::doSelect($c);
      foreach ($tblblogs as $tblblog) {
        $blogName = $tblblog->getBlShortName();
        echo $tblblog->getBlId().' '.$blogName."<br>";
        $tblblog->delete();
        blogStore::getCache()->remove($blogName, 'blogs');
      }
      return sfView::NONE;
    }
    $blogId = $this->getRequestParameter('blogId');
    $blogName = $this->getRequestParameter('blogName');
    if ($blogId) {
      $tblblog = TblblogPeer::retrieveByPK($blogId);
      $blogName = $tblblog->getBlShortName();
    }
    if ($blogName) {
      $c = new Criteria();
      $c->add(TblblogPeer::BL_SHORTNAME, $blogName);
      $tblblog = TblblogPeer::doSelectOne($c);
      $blogId = $tblblog->getBlId();
    }
    if ($tblblog && $tblblog->getBlId()>=100) $tblblog->delete();
    blogStore::getCache()->remove($blogName, 'blogs');
    sfLoader::loadHelpers('tvtl', 'block');
    cache_include_reset($blogId);
    $this->redirect('/');
  }

  /**
   * function: display nick yahoo support
   * Display screen edit nick and infor
   *
   */
  public function executeListsupport() {
    $this->listSupport = @blogStore::$moduleConfig['modules']['support']['items'];
  }

  public function executeEditsupport() {
    $listSupport = @blogStore::$moduleConfig['modules']['support']['items'];
    $this->key = $this->getRequestParameter('key', '');
    if ($this->key!='') $this->support = $listSupport[$this->key];
  }

  public function executeUpdatesupport() {
    $listSupport = @blogStore::$moduleConfig['modules']['support']['items'];
    $current = $this->getRequestParameter('key', '');
    $nick = $this->getRequestParameter('nick', '');
    $name = $this->getRequestParameter('name', '');
    $atpos = strpos($nick, '@');
    if ($atpos!==false) $nick = substr($nick, 0, $atpos);
    $support = array('nick'=>$nick, 'name'=>$name);
    if ($current=='') $listSupport[] = $support;
    else $listSupport[$current] = $support;
    blogStore::$moduleConfig['modules']['support']['items'] = $listSupport;
    $this->updateConfig();
    $this->forward('admin', 'listsupport');
  }

  /**
   * Update order of support
   *
   */
  public function executeUpdateordersupport() {
    $key = $this->getRequestParameter('key');
    $order = $this->getRequestParameter('order');
    $listSupport = &blogStore::$moduleConfig['modules']['support']['items'];
    $item = array_splice($listSupport, $key, 1);
    array_splice($listSupport, $order-1, 0, $item);
    $this->updateConfig();
    $this->forward('admin', 'listsupport');
  }

  /**
   * Delete support
   *
   */
  public function executeDelsupport() {
    $nicks = $this->getRequestParameter('id');
    $nicks = split('\|',$nicks);

    $listSupport = &blogStore::$moduleConfig['modules']['support']['items'];
    foreach($listSupport  as $key=>$item) {
      if(in_array($item['nick'],$nicks)) {
        unset($listSupport[$key]);
      }
    }
    $this->updateConfig();
    $this->forward('admin', 'listsupport');
  }

  public function executeListblogentry() {
    $this->entry_type = $this->getRequestParameter('entry_type', '');
    //$this->keyword = $this->getRequestParameter('keyword', '');
    $blogId = blogStore::$blogId;
    $c = new Criteria();

    $c->add(TblblogentryPeer::ENTRY_BLOG,$blogId);
    $c->addIndex('blogallindex');
    $c->addDescendingOrderByColumn(TblblogentryPeer::ENTRY_MODIFYDATE);
    if ($this->entry_type != '')
      $c->add(TblblogentryPeer::ENTRY_TYPE,$this->entry_type);
    $this->page = $this->getRequestParameter('page', 1);
    $this->pager = new PropelPager($c, 'TblblogentryPeer', 'doSelect', $this->page, 20);
  }

  public function executeDeleteEntry() {
    $entry_ids = $this->getRequestParameter('entry');
    foreach ($entry_ids as $entry_id) {
      $tblblogentry = TblblogentryPeer::retrieveByPK($entry_id);
      if ($tblblogentry && $tblblogentry->canDeleteEntry()) {
        $tblblogentry->setEntryStatus(2);
        $tblblogentry->save();
      }
    }
    $this->redirect('/admin/listblogentry');
  }

  /**
   * List entry invalid
   */
  public function executeListentryinvalid() {
    $c = new Criteria() ;
    $c->add(TbluserPeer::US_ID,blogStore::$userId);
    $tbluser = TbluserPeer::doSelect($c);
    $this->forward404Unless(blogStore::isAdministator());
    $c = new Criteria();
    $c->add(TblblogentryinvalidPeer::EI_BLOG,blogStore::$blogId);
    $c->addDescendingOrderByColumn(TblblogentryinvalidPeer::EI_DATESENT);
    $this->page = $this->getRequestParameter('page', 1);
    $this->pager = new PropelPager($c, 'TblblogentryinvalidPeer', 'doSelect', $this->page, 20);
  }

  /**
   * Show entry invalid
   *
   * @return unknown
   */
  public function executeShowentryinvalid() {
    $this->entry_id = $this->getRequestParameter('id');
    $this->tblblogentry = TblblogentryPeer::retrieveByPK($this->entry_id);
    $this->forward404Unless($this->tblblogentry != null);
    $this->type = $this->tblblogentry->getEntryType();
    if($this->type == 0) {
      $this->tblpresentation = TblpresentationPeer::retrieveByPk($this->tblblogentry->getEntryLink());
    } elseif($this->type == 1) {
      $this->tbldocument = TbldocumentPeer::retrieveByPk($this->tblblogentry->getEntryLink());
    }
  }

  /**
   * function reactive entry be delete
   */
  public function executeReactive() {
    $entrys = $this->getRequestParameter('entry');
    foreach($entrys as $entry) {
      //set status for entry 2
      $tblblogentry = TblblogentryPeer::retrieveByPK($entry);
      $tblblogentry->setEntryStatus(0);
      $tblblogentry->save();

      //delete from tblblogentryinvalid
      $tblblogentryinvalid = TblblogentryinvalidPeer::retrieveByPK($entry);
      $tblblogentryinvalid->delete();
    }
    $this->redirect($this->getRequest()->getReferer());
  }

  /**
   * show menu manager window
   * @author quangnp
   */
  function getMenuPath() {
     preg_match('/^(^\D+)(.*)$/', $this->type, $match);
     switch ($match[1]) {
      case 'hor':
        return 'menus';
        break;
      case 'ver':
        return 'modules/leftmenu'.$match[2].'/content';
        break;
      default:
        $this->forward404('Không có kiểu menu '.$this->type);
    }
  }

  /**
   * show menu manager window
   * @author quangnp
   */
  public function executeMenu() {
    $this->type = $this->getRequestParameter('type', 'hor');
    $config = blogStore::getParam($this->getMenuPath());
    if ($config=='') {
      $config = array();
    }
    $menu = new blogMenuManager($config);
    $this->menu = $menu->getJavascriptObject();

    $config = sfConfig::get('mod_admin_standard_config');
    $menu = new blogMenuManager($config['all']['menus']);
    $this->menu_template = $menu->getJavascriptObject();

    $menu = new blogMenuManager(blogMenuManager::buildEntryMenu());
    $this->menu_entry = $menu->getJavascriptObject();
  }

  /**
   * Save menu from 'menu' parameter
   * @return unknown
   * @author quangnp
   */
  public function executeSavemenu() {
    try {
      $this->type = $this->getRequestParameter('type', 'hor');
      $menu_path = $this->getMenuPath();
      $menu = $this->getRequestParameter('menu');
      $menu = htmlspecialchars_decode($menu);
      $menu = sfYaml::load($menu);
      blogStore::setParam($menu_path, $menu);
      if ($this->type=='ver') {
        blogStore::setParam('modules/leftmenu/pos', 'left');
      }
      blogStore::$blog->setBlModuleConfig(sfYaml::dump(blogStore::$moduleConfig));
      blogStore::$blog->save();
      blogStore::resetCache();
      return $this->renderText('OK');
    } catch (Exception $e) {
      return sfView::NONE;
    }
  }

  public function executeAddmenu() {
    $typeBlog = blogStore::getParam('config/type', 'all');
    $moduleConfigDefault = sfConfig::get('mod_admin_standard_config');
    $moduleConfigDefault = $moduleConfigDefault[$typeBlog];
    $i = 1;
    while (@blogStore::getParam('modules/leftmenu'.$i)) $i++;
    $name = 'leftmenu'.$i;
    $moduleConfig = &blogStore::$moduleConfig;
    $moduleConfig['modules'][$name] = $moduleConfigDefault['modules']['leftmenu'];
    $moduleConfig['modules'][$name]['name'] = $moduleConfigDefault['modules']['leftmenu']['name'].' '.$i;

    $this->updateConfig('menu?type=ver'.$i);
  }

  /**
   * Enter description here...
   *
   */
  public function executeTestblog() {
    $c = new Criteria();
    $tblblogs = TblblogPeer::doSelect($c);
    foreach ($tblblogs as $tblblog) {
      $moduleConfig = sfYaml::load($tblblog->getBlModuleConfig());
      if (@$moduleConfig['menus']['admin']==null || @$moduleConfig['menus']['admin']['allow'] != 'blogadmin') echo $tblblog->getBlId().'<br>';
    }
    exit;
  }

  /**
   * Enter description here...
   *
   */
  public function executeUpdatelayout() {
    blogStore::$moduleConfig['layout'] = $this->getRequestParameter('theme-select', 'standard');
    $this->updateConfig('index');
  }

  /**
   * Check if this blog can have subdomain or not
   *
   * @return unknown
   */
  public function executeCheckhost() {
    if (blogStore::$isRoute) return sfView::NONE;
    if (blogStore::$blog->getBlHost()!=null) return sfView::NONE;

    $id = blogStore::$blogId;
    $startdate = date('Y-m-d', strtotime('-7 day'));
    $enddate = date('Y-m-d', strtotime('-1 day'));

    $this->sumPoint = myUtility::execSql("select sum(std_visitors) from tblblogstatday where std_blog=$id and
      std_date between '$startdate' and '$enddate'");

    if (null!=$this->sumPoint ) {
      $this->sumPoint = $this->sumPoint[0][0];
    }
    if (null==$this->sumPoint) $this->sumPoint = 0;

    $this->minPoint = 700;
  }

  /**
   * Create subdomain of blog
   *
   * @return unknown
   */
  public function executeSubdomain() {
    try {
      $code = $this->getRequestParameter('code');
      if ($code!=md5(blogStore::$blogId)) throw new Exception();
      $host = strtolower(blogStore::$blogName . '.' . sfConfig::get('app_base_host'));
      $check = TblbloghostPeer::retrieveByPK($host);
      if ($check) return $this->renderText('Xin loi, ten mien nay da duoc su dung');

      $tbluser = TbluserPeer::retrieveByPK(blogStore::$blog->getBlUser());
      $tbluser->setUsHomepage(null);
      $tbluser->save();

      $bloghost = new Tblbloghost();
      $bloghost->setBhHost($host);
      $bloghost->setBhBlogname(blogStore::$blogName);
      $bloghost->save();

      blogStore::resetNewRoute($host);

      blogStore::$blog->setBlHost($host);
      blogStore::$blog->save();
      blogStore::resetCache();

      $this->redirect('http://'.$host);
    } catch (Exception $e) {
      return $this->renderText('Xin loi, yeu cau khong hop le');
    }
  }

  public function executeResethost() {
    $code = $this->getRequestParameter('code');
    $memcache = blogStore::getCache();
    $memcache->remove('route'.$code, '');
    $this->redirect('/');
  }

  /**
   * Enter description here...
   *
   */
  public function executeAdvanced() {
    $this->newDisplayStyle = blogStore::getNewsStyle();
    $this->displayStyle = blogStore::getDisplayStyle();
    $this->moduleConfig = blogStore::$moduleConfig;
    $this->listAdverts = @$this->moduleConfig['adverts'];
    $this->index = 0;
    $this->blocktype = sfConfig::get('mod_admin_advert_position');
  }

  /**
   * update news displaying type
   *
   */
  public function executeUpdatelayoutNews() {
    $displayStyle = $this->getRequestParameter('display-style');
    if ($displayStyle) blogStore::$moduleConfig['config']['display-style'] = $displayStyle;
    $newDisplayStyle = $this->getRequestParameter('news-display-style');
    if ($newDisplayStyle) blogStore::$moduleConfig['config']['news-display-style'] = $newDisplayStyle;
    $this->updateConfig('advanced');
  }

  /**
   * Manage user defined module
   */
  public function executeEditmodule() {
    $this->moduleName = $this->getRequestParameter('modulename');
    $this->position = $this->getRequestParameter('pos');
    $this->display_page = 0;
    $this->display_mode = 0;
    $this->display_page_list = array(
      'Tất cả các trang',
      'Chỉ ở trang chủ',
    );
    $this->display_mode_list = array(
      'Luôn luôn hiển thị',
      'Chỉ hiện khi chưa đăng nhập',
      'Chỉ hiện khi đã đăng nhập',
      'Chỉ hiện đối với quản trị',
    );
    if ($this->moduleName) { //edit an existed module
      $module = @blogStore::$moduleConfig['modules'][$this->moduleName];
      $this->title = @$module['name'];
      $this->embed = @$module['embed'];
      if (@$module['show']=='home.*') $this->display_page = 1;
      if (@$module['deny']=='user') $this->display_mode = 1;
      if (@$module['allow']=='user') $this->display_mode = 2;
      if (@$module['allow']=='admin') $this->display_mode = 3;
    }
  }

  public function executeUpdatemodule() {
    $moduleName = $this->getRequestParameter('modulename');
    $display_page = $this->getRequestParameter('display_page');
    $display_mode = $this->getRequestParameter('display_mode');
    if (!$moduleName) { //create new module
      $id = 1;
      while (isset(blogStore::$moduleConfig['modules']['block'.$id])) $id++;
      $moduleName = 'block'.$id;
      $pos = $this->getRequestParameter('pos', 'center');
      blogStore::$moduleConfig['modules'][$moduleName] = array('pos'=>$pos);
    }
    $module = &blogStore::$moduleConfig['modules'][$moduleName];
    if ($display_page==0) {unset($module['hide']); unset($module['show']);}
    if ($display_page==1) {$module['hide']='*.*'; $module['show']='home.*';}
    if ($display_mode==0) {unset($module['deny']); unset($module['allow']);}
    if ($display_mode==1) $module['deny']='user';
    if ($display_mode==2) $module['allow']='user';
    if ($display_mode==3) $module['allow']='blogadmin';
    $module['name'] = $this->getRequestParameter('title');
    $embed = $this->getRequestParameter('embed');
    $validated_embed = htmlFilter::validateHtml($embed);
    $module['embed'] = $validated_embed;
    $this->updateConfig('module');
  }

  public function executeDeletemodule() {
    $moduleName = $this->getRequestParameter('modulename');
    unset(blogStore::$moduleConfig['modules'][$moduleName]);
    $this->updateConfig('module');
  }

  /**
   * For refblogs block configuration
   */
  public function executeListrefblog() {
   $configs = blogStore::$moduleConfig;
   $this->params = $configs['modules']['refblogs']['params'];
  }

  public function executeSearchblog() {
    $content = $this->getRequestParameter('content');
    $c = new Criteria();
    $c->add(TblblogPeer::BL_SHORTNAME,'%'.$content.'%', Criteria::LIKE);
    $c->setLimit(10);
    $this->blogs = TblblogPeer::doSelect($c);
  }

  public function executeUpdateListblogs() {
    $bl_id = $this->getRequestParameter('bl_id');
    $bl_host = $this->getRequestParameter('bl_host');
    $bl_title = $this->getRequestParameter('bl_title');
    $bl_list = $this->getRequestParameter('bl_list');
    for ($i = 0; $i < count($bl_id); $i++) {
      $params['blog'.$i] = array(
        'id'   => $bl_id[$i],
        'name' => $bl_title[$i],
        'url'  => $bl_host[$i],
        'list' => $bl_list[$i]);
    }
    blogStore::$moduleConfig['modules']['refblogs']['params'] = $params;
    $this->updateConfig();
    return $this->renderText('Đã lưu');
  }

  /**
   * Manage user advertisement
   */
  public function executeEditadvert() {
    $this->block = $this->getRequestParameter('block');
    $this->advert = $this->getRequestParameter('advert');
    $this->item = @blogStore::$moduleConfig['adverts'][$this->block][$this->advert];
    $this->blocklist = sfConfig::get('mod_admin_advert_position');
    foreach (blogStore::$moduleConfig['modules'] as $key=>$module)
      if (substr($key, 0, 5) == 'block')
        $this->blocklist[$key] = @$module['name']?$module['name']:$key;
    for ($i=0; $i<count(blogStore::$catTree->tree); $i++)
      $this->blocklist['inside'.$i] = 'Giữa nội dung chính, ở dưới '.$i.' đề mục';
  }

  public function executeUpdateadvert() {
    $action = $this->getRequestParameter('act', 0);
    $block = $this->getRequestParameter('block');
    $advert = $this->getRequestParameter('advert');
    $advlist = &blogStore::$moduleConfig['adverts'][$block];
    switch ($action) {
    case 0:  //create new or update advert with editor form
      $oldblock = $this->getRequestParameter('oldblock');
      if ($oldblock != null && $oldblock != $block) {
        unset(blogStore::$moduleConfig['adverts'][$oldblock][$advert]);
      }
      if (!$advert) { //create new
        $id = 1;
        while (isset($advlist['advert'.$id])) $id++;
        $advert = 'advert'.$id;
      }
      $item = &$advlist[$advert];
      $item['title'] = $this->getRequestParameter('title');
      $item['imgUrl'] = $this->getRequestParameter('imgUrl');
      $item['embed'] = $this->getRequestParameter('embed');
      $item['link'] = $this->getRequestParameter('link');
      $pos = $this->getRequestParameter('pos');
      $gap = $this->getRequestParameter('gap');
      if ($pos) $item['pos'] = $pos; else unset($item['pos']);
      if ($gap) $item['gap'] = $gap; else unset($item['gap']);
      if ($size = $this->getRequestParameter('size')) {
        $dim = split('x', $size);
        $item['width'] = $dim[0];
        $item['height'] = $dim[1];
      } else {
        unset($item['width']);
        unset($item['height']);
      }
      break;
    case 1:  //hide or show advert
      $visible = $this->getRequestParameter('visible', '1');
      $advlist[$advert]['visible'] = $visible;
      break;
    case 2:  //update advert order
      $pos = $this->getRequestParameter('order') - 1;
      $item = $advlist[$advert];
      unset($advlist[$advert]);
      $advlist = array_slice($advlist, 0, $pos) + array($advert=>$item) + array_slice($advlist, $pos);
      break;
    case 3:  //delete advert
      unset($advlist[$advert]);
      break;
    }
    $this->updateConfig('advanced');
  }

  public function executeResetadverts() {
    if (blogStore::$blogName != 'main') return;
    $c = new Criteria();
    $c->add(TblblogPeer::BL_ID, 10, Criteria::GREATER_THAN);
    $c->add(TblblogPeer::BL_ID, 100, Criteria::LESS_THAN);
    $refblogs = TblblogPeer::doSelect($c);
    foreach ($refblogs as $refblog) {
      $refmc = sfYaml::load($refblog->getBlModuleConfig());
      $refmc['adverts'] = blogStore::$moduleConfig['adverts'];
      $refblog->setBlModuleConfig(sfYaml::dump($refmc));
      $refblog->save();
      blogStore::getCache()->remove($refblog->getBlShortname(), 'blogs');
    }
    $this->redirect('/');
  }

  public function executeSetcommerce() {
    $this->tbluser = TbluserPeer::retrieveByPk(blogStore::$userId);
    $this->priceList = sfConfig::get('app_upgrade_blog_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');
        $this->buy = $amount[0];
      } else {
        $tblblog = TblblogPeer::retrieveByPk(blogStore::$blogId);
        $start = $tblblog->getBlCommercial()? $tblblog->getBlCommexpire(): date('Y-m-d H:i:s');
        $tblblog->setBlCommexpire(date('Y-m-d H:i:s', strtotime($start.' + 1 '.$amount[0])));
        $tblblog->save();
        $this->tbluser->doTransaction(-$amount[1], 'pay', 'commerce '.$amount[0]);
        blogStore::resetCache();
        return $this->renderText("<h3>Thiết lập thành công</h3><script>Modalbox.hide(); location.reload();</script>");
      }
    }
  } 
}
