<?php

/**
 * blog actions.
 *
 * @package    violet
 * @subpackage blog
 * @author     Dinh Hai Minh
 */
class blogActions extends sfMyActions
{
  public function executeListblogmember() {
    myUtility::log($this->getRequest()->getUri(), 'listblogmember.log');
    return $this->redirect('/user/list');
  }

  public function executeListsubblog() {
    $this->blogtype = $this->getRequestParameter('blogtype', 0);
    $this->sort = $this->getRequestParameter('sort', 'id');
    $this->order_by = $this->getRequestParameter('order_by', 'asc');
    $this->titlestatus = '';
    $this->hitstatus = '';

    $down = '<font size="3">↓</font>';
    $up = '<font size="3">↑</font>';

    $c = new Criteria();
    switch ($this->sort) {
      case 'title':
        $this->titlestatus = $this->order_by == 'desc' ? $down : $up;
        $this->order_by == 'desc' ? $c->addDescendingOrderByColumn(TblblogPeer::BL_TITLE) : $c->addAscendingOrderByColumn(TblblogPeer::BL_TITLE );
        break;
      case 'hit':
        $this->hitstatus = $this->order_by == 'desc' ? $down : $up;
        $this->order_by == 'desc' ? $c->addDescendingOrderByColumn(TblblogPeer::BL_HIT) : $c->addAscendingOrderByColumn(TblblogPeer::BL_HIT );
        break;
    }
    $c->addDescendingOrderByColumn(TblblogPeer::BL_ID);
    $this->page = $this->getRequestParameter('page', 1);

    if (blogStore::$blogName=='main') {
      if ($this->blogtype>0) $c->add(TblblogPeer::BL_TYPE, $this->blogtype);
      else $c->add(TblblogPeer::BL_ID, 100, Criteria::GREATER_EQUAL);
      $this->pager = new PropelPager($c, 'TblblogPeer', 'doSelect', $this->page, 20);
    } else {
      $c->add(TblblogdependsPeer::DP_PARENT, blogStore::$blogId);
      $this->pager = new PropelPager($c, 'TblblogdependsPeer', 'doSelectJoinTblblog', $this->page, 20);
    }
  }

  public function executeCreateweb() {
    $this->message = '';
    $tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
    $tbluserinfo = TblblogcheckinfoPeer::retrieveByPK(blogStore::$userId);

    //kiem tra dinh danh
    if ($tbluser->getUsChecked() == 0) {
      $link = $this->getController()->genUrl('/user/show', true);
      $this->message = "Quý vị chưa được xác thực nên không thể tạo trang riêng, click <a href='".$link."'>vào đây</a> để xác thực";
      return sfView::SUCCESS;
    }

    if($tbluserinfo) {
      $tblprovince = TblblogschoolsPeer::retrieveByPK($tbluserinfo->getCiProvince());
      $tbldistrict = TblblogschoolsPeer::retrieveByPK($tbluserinfo->getCiDistrict());
      $tblschool = TblblogschoolsPeer::retrieveByPK($tbluserinfo->getCiSchool());

      //lay ten blog cua so
      if ($tblprovince) {
        $blog_province = myUtility::getUrlName($tblprovince->getScName());
      }
      //lay ten blog cua phong
      if ($tbldistrict) {
        $blog_district = myUtility::getUrlName($tbldistrict->getScName());
        $blog_district = preg_replace('@^(huyen|quan|thixa|thanhpho)@', '', $blog_district);
        if ($blog_district == $blog_province) $blog_district = 'phong'.$blog_district;
        $blog_district_2 = $blog_district . '-' . $blog_province;
      }
      //lay ten blog cua truong
      if ($tblschool) {
        $blog_school = blogStore::$sc_prefix[$tblschool->getScType()];
        $school_name = preg_replace('@^(Trường)@', '', $tblschool->getScName());
        $school_name = preg_replace('@^(Tiểu học|THCS|THPT|PTTH|PTCS|Phổ thông|Mầm non)@', '', trim($school_name));
        $school_name = str_replace('Sư phạm', 'SP', $school_name);
        $blog_school .= myUtility::getUrlName($school_name);
        $blog_school_2 = $blog_school . '-' . $blog_district . '-' . $blog_province;
        if (!preg_match("@$blog_province$@", $blog_school)) $blog_school .= '-' . $blog_province;
      }

      //get cac blog cua so, phong, truong
      $c = new Criteria();
      $c->add(TblblogPeer::BL_SCHOOL, $tbluserinfo->getCiProvince());
      $this->blog_province = TblblogPeer::doSelectOne($c);
      $c = new Criteria();
      $c->add(TblblogPeer::BL_SCHOOL, $tbluserinfo->getCiDistrict());
      $this->blog_district = TblblogPeer::doSelectOne($c);
      $c = new Criteria();
      $c->add(TblblogPeer::BL_SCHOOL, $tbluserinfo->getCiSchool());
      $this->blog_school = TblblogPeer::doSelectOne($c);

      $this->province = $tblprovince;
      $this->district = $tbldistrict;
      $this->school = $tblschool;
      $this->parentBlog = '';
      $this->parentSelected = 'violet';
      $this->username = $tbluser->getUsUsername();
      $this->position = $tbluserinfo->getCiPosition();

      //**************************************************************
      // Cán bộ Sở GD&ĐT tạo trang web
      if ($this->position > 0 && $this->position < 10) {
        $this->title = 'Website Sở GD&ĐT '.$tblprovince->getScName();
        $this->name = $blog_province;
        $this->blogtype = 4;
        $menutype = 0;
      }
      //**************************************************************
      // Cán bộ Phòng GD&ĐT tạo trang web
      elseif ($this->position < 20 && $this->position > 9 ) {
        $this->title = 'Website Phòng GD&ĐT '.$tbldistrict->getScName();
        $this->name = $blog_district;

        //Kiểm tra đã có trang huyện nào trùng tên chưa
        $c = new Criteria();
        $c->add(TblblogPeer::BL_SHORTNAME, $this->name);
        $tblexist = TblblogPeer::doSelectOne($c);
        if ($tblexist) {
          $bladmin = TblblogcheckinfoPeer::retrieveByPK($tblexist->getBlUser());
          if ($bladmin->getCiDistrict() != $tbluserinfo->getCiDistrict()) $this->name = $blog_district_2;
        }

        //Chọn trang web cấp trên
        if ($this->blog_province) {
          $this->parentBlog = $this->blog_province->getBlId();
          $this->parentSelected = 'province';
        }
        $this->blogtype = 3;
        $menutype = 1;
      }
      //**************************************************************
      // Cán bộ Trường tạo trang web
      elseif ($this->position < 40 && $this->position > 19) {
        $this->title = 'Website của '.$tblschool->getScName();
        $this->titlePersonal = 'Website của '.$tbluser->getUsFullname();
        $this->name = $blog_school;

        //Kiểm tra xem đã có trường nào có tên thế này chưa
        $c = new Criteria();
        $c->add(TblblogPeer::BL_SHORTNAME, $this->name);
        $c->add(TblblogPeer::BL_TYPE, 2);
        $tblblog_checkschool = TblblogPeer::doSelectOne($c);
        if ($tblblog_checkschool) {
          $bladmin = TblblogcheckinfoPeer::retrieveByPK($tblblog_checkschool->getBlUser());
          if ($bladmin && $bladmin->getCiSchool() != $tbluserinfo->getCiSchool()) $this->name = $blog_school_2;
        }

        //Chọn trang web cấp trên
        if ($this->blog_province) {
          $this->parentBlog = $this->blog_province->getBlId();
          $this->parentSelected = 'province';
        }
        //truong THPT thi khong truc thuoc Phong GD&DT
        if ($this->blog_district && $tblschool->getScType()!=4) {
          $this->parentBlog = $this->blog_district->getBlId().($this->parentBlog!=''? (','.$this->parentBlog): '');
          $this->parentSelected = 'district';
        }
        //Chọn trang web cấp trên cho website giáo viên
        if ($this->blog_school) {
          $this->parentBlogTeacher = $this->blog_school->getBlId().($this->parentBlog!=''? (','.$this->parentBlog): '');
          $this->parentSelectedTeacher = 'school';
        } else {
          $this->parentBlogTeacher = $this->parentBlog;
          $this->parentSelectedTeacher = $this->parentSelected;
        }
        $this->blogtype = 2;
        $menutype = $tblschool->getScType();
      }
      //**************************************************************
      // Không phải Giáo viên hoặc Cán bộ QLGD tạo trang web
      else {
        $this->titlePersonal = 'Website của '.$tbluser->getUsFullname();
        $this->name = myUtility::getUrlName($this->username);
        $this->parentBlogTeacher = '';
        $this->parentSelectedTeacher = 'violet';
        $menutype = $this->position;
      }

      $this->tempId = array(0=>'&lt;Chọn mẫu thư viện&gt;');
      foreach (blogStore::$sc_menus[$menutype] as $i) {
        $this->tempId[$i] = blogStore::$blogTitle[$i];
      }
    }
  }

  private function replaceCatId($menucontent) {
    foreach ($menucontent as $key => $item) {
      $link = $item['link'];
      $pattern = '@cat_id(/|=)([0-9]+)@';
      preg_match($pattern, $link, $cat_id);
      $newparam = 'cat_id${1}'.@$this->catcopy[$cat_id[2]];
      $menucontent[$key]['link'] = preg_replace($pattern, $newparam, $link);
      if (array_key_exists('child', $item)) {
        $menucontent[$key]['child'] = $this->replaceCatId($item['child']);
      }
    }
    return $menucontent;
  }

  public function executeUpdateweb() {
    $this->forward404If($this->getRequest()->getMethod() != sfRequest::POST, 'Phương thức truy cập không hợp lệ');
    $blogdefaultName = blogStore::$blogDefault[$this->getRequestParameter('rights')];
    $weburl = $this->getRequestParameter('shortname');
    $shortname = str_replace('http://violet.vn/', '', $weburl);
    $this->error = null;
    $bltype = $this->getRequestParameter('bltype', 1);

    myUtility::log("Start create web ($shortname)", 'createweb.log', "\n");
    //check xem block da ton tai chua
    $c = new Criteria();
    $c->add(TblblogPeer::BL_SHORTNAME,$shortname);
    $tblblogexist = TblblogPeer::doSelectOne($c);
    if ($tblblogexist) {
      $adminid = $tblblogexist->getBlUser();
      $bladmin = TbluserPeer::retrieveByPK($adminid);
      $link = $this->getController()->genUrl('/user/show', true);
      $this->error = '<a href="'.$weburl.'">Trang web này</a> đã tồn tại do <a href="'.$link.'?id='.$adminid.'">'.$bladmin->getUsFullname().'</a> quản lý';
      return sfView::SUCCESS;
    }

    //kiem tra xem mau thu vien nay da co trong database chua
    $c = new Criteria();
    $c->add(TblblogPeer::BL_SHORTNAME,$blogdefaultName);
    $tblblog_template = TblblogPeer::doSelectOne($c);
    if($tblblog_template == null) {
      $this->error = 'Mẫu thư viện này chưa tồn tại';
      return sfView::SUCCESS;
    } else {
      myUtility::log("Create blog database ($shortname)", 'createweb.log');
      $blogIdDefault = $tblblog_template->getBlId();
      $configDefault = sfYaml::load($tblblog_template->getBlModuleConfig());
      $bannerDefault = @$configDefault['config']['banner']['url'];
      $backgroundDefault = @$configDefault['config']['background']['url'];
      $title = $this->getRequestParameter('bltitle');
      $user_id = blogStore::$userId;
      $school_id = $this->getRequestParameter('school_id', '');
      $district_id = $this->getRequestParameter('district_id', '');
      $province_id = $this->getRequestParameter('province_id', '');

      $tbluser = TbluserPeer::retrieveByPK($user_id);
      $tbluser->setUsHomepage(null);
      $tbluser->save();

      $tblblog = new Tblblog();
      $tblblog->setBlShortname($shortname);
      $tblblog->setBlTitle($title);
      $tblblog->setBlUser($user_id);
      $tblblog->setBlModuleConfig($tblblog_template->getBlModuleConfig());
      $tblblog->setBlType($bltype);
      $tblblog->setBlLastupdate(date('Y-m-d H:i:s'));
      if ($bltype==2) $tblblog->setBlSchool($school_id);
      if ($bltype==3) $tblblog->setBlSchool($district_id);
      if ($bltype==4) $tblblog->setBlSchool($province_id);
      $tblblog->save();
      $blogId = $tblblog->getBlId();

      // neu tao trang web rong thi khong thuc hien copy thu muc
      myUtility::log("Copy blog data ($shortname)", 'createweb.log');
      if($this->getRequestParameter('rights') != 'empty') {
        if ($bltype > 1) {//blog cua don vi
          $this->createCopyStandard($blogIdDefault, $blogId);
        } else {
          $tbluserinfo = TblblogcheckinfoPeer::retrieveByPK($user_id);
          $subjects = $tbluserinfo->getCiSubject();
          $this->createCopyStandard($blogIdDefault, $blogId, $subjects);
        }
      }

      myUtility::log("Update leftmenu, poll, relationship ($shortname)", 'createweb.log');
      //update left menu
      $moduleConfig = sfYaml::load($tblblog->getBlModuleConfig());
      if (array_key_exists('leftmenu', $moduleConfig['modules'])) {
        $menucontent = &$moduleConfig['modules']['leftmenu']['content'];
        $menucontent = $this->replaceCatId($menucontent);
        $tblblog->setBlModuleConfig(sfYaml::dump($moduleConfig));
        $tblblog->save();
      }

      //get all poll of this blog
      $c = new Criteria();
      $c->add(TblblogpollPeer::POLL_BLOG, $blogIdDefault);
      $tblblogpolls = TblblogpollPeer::doSelect($c);
      foreach($tblblogpolls as $tblblogpoll) {
        $tblpoll = new Tblblogpoll();
        $tblpoll->setPollName($tblblogpoll->getPollName());
        $tblpoll->setPollQuestions($tblblogpoll->getPollQuestions());
        $tblpoll->setPollType($tblblogpoll->getPollType());
        $tblpoll->setPollBlog($blogId);
        $tblpoll->setPollCreatedate($tblblogpoll->getPollCreatedate());
        $tblpoll->setPollActive($tblblogpoll->getPollActive());
        $tblpoll->save();
      }

      //manhtl: luu quan he blog
      if ($this->getRequestParameter('blparent', 0) != 0) {
        $parents = explode(',', $this->getRequestParameter('blparent'));
        foreach ($parents as $parent) {
          $tblblogdepend = new Tblblogdepends();
          $tblblogdepend->setDpBlog($blogId);
          $tblblogdepend->setDpParent($parent);
          $tblblogdepend->save();
        }
      }

      //luu quan he voi cac blog con
      if ($bltype > 1) {
        $schoolId = $tblblog->getBlSchool();
        $childschools = myUtility::execSql("select sc_id from tblblogschools
          where sc_parent=$schoolId or sc_parent in (select sc_id from tblblogschools where sc_parent=$schoolId)");
        $childschoolids = array();
        foreach ($childschools as $child) {
          $childschoolids[] = $child[0];
        }
        $c = new Criteria();
        $c->add(TblblogPeer::BL_SCHOOL, $childschoolids, Criteria::IN);
        $schoolBlogs = TblblogPeer::doSelect($c);
        foreach ($schoolBlogs as $schoolBlog) {
          $tblblogdepend = new Tblblogdepends();
          $tblblogdepend->setDpBlog($schoolBlog->getBlId());
          $tblblogdepend->setDpParent($blogId);
          $tblblogdepend->save();
        }
      }

      //gia nhập trang riêng
      myUtility::log("Join members to this blog ($shortname)", 'createweb.log');
      if ($bltype > 1) {
        //tim tat ca user thuoc don vi nay cho lam` thanh vien cua trang rieng nay
        $c = new Criteria();
        if ($bltype==2) $c->add(TblblogcheckinfoPeer::CI_SCHOOL, $school_id);
        if ($bltype==3) $c->add(TblblogcheckinfoPeer::CI_DISTRICT, $district_id);
        if ($bltype==4) $c->add(TblblogcheckinfoPeer::CI_PROVINCE, $province_id);
        $c->add(TbluserPeer::US_CHECKED, 1);
        $tblblogcheckinfos = TblblogcheckinfoPeer::doSelectJoinTbluser($c);
      } else {
        // cho admin gia nhập trang riêng
        $tblblogcheckinfo = new Tblblogcheckinfo();
        $tblblogcheckinfo->setCiUserid(blogStore::$userId);
        $tblblogcheckinfos = array($tblblogcheckinfo);
      }
      if ($tblblogcheckinfos) {
        foreach ($tblblogcheckinfos as $tblblogcheckinfo) {
          $tblbloguser =  new Tblbloguser();
          $tblbloguser->setUsBlog($blogId);
          $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();
        }
      }

      // tao thu muc cua blog
      myUtility::log("Create blog directories ($shortname)", 'createweb.log');
      $folder = blogStore::getBlogFolder(true, $blogId);
      umask(0);
      mkdir($folder, 0777, true);
      mkdir($folder.'/js', 0777, true);
      mkdir($folder.'/layout', 0777, true);
      mkdir($folder.'/entrythumb', 0777, true);

      $this->shortname = $shortname;
      $this->copyData($blogIdDefault, $blogId, $backgroundDefault, $bannerDefault);
      $this->getUser()->getAttributeHolder()->remove('myblog');
      $this->getUser()->getAttributeHolder()->remove('ismember');
      sfContext::getInstance()->getUser()->clearBlogmember();
      myUtility::log("Finish create web ($shortname)", 'createweb.log');
    }
  }
  /**
   * function: create copy of category tree
   * of blog standard
   * params: name of blog standard
   * return: new rows is copy of blog standard
   */
  public function createCopyStandard($blogId, $newBlogId, $subjects='') {
    //array store relation of row id and copy row id
    $copy = array();
    if ($subjects == '') {
      //get all category in this blog
      $c = new Criteria();
      $c->add(TblblogcategoryPeer::CAT_BLOG, $blogId);
      $tblblogcategory = TblblogcategoryPeer::doSelect($c);
    } else {
      //get danh sach cac mon hoc cua giao vien de tao category
      $cat_ids = explode(',', $subjects);
      foreach ($cat_ids as $id) {
        $cat1 = @blogStore::$subject1[$id];
        $cat2 = @blogStore::$subject2[$id];
        $cat_attach[] = $cat1? $cat1: $cat2;
      }
      //get tat ca cac category ma giao vien da chon va bai viet
      $cat_attach = array_merge($cat_attach, array('Bài viết'));
      $c = new Criteria();
      $c->add(TblblogcategoryPeer::CAT_BLOG,$blogId);
      $c->add(TblblogcategoryPeer::CAT_NAME, $cat_attach, Criteria::IN);
      $tblblogcategory_selected = TblblogcategoryPeer::doSelect($c);
      foreach ($tblblogcategory_selected as $tblblogcategory) {
        $catpaths = explode(',', $tblblogcategory->getCatPath());
        if (count($catpaths) > 2) continue; //khong copy cac thu muc tu cap 3 tro len
        $ids[] = $tblblogcategory->getCatId();
      }
      //get tat ca thu muc cua blog mau ma giao vien da chon
      $regString = 'cat_path regexp "'. join('(,*)|', $ids) . '|(^[0-9]*$)"';
      $c = new Criteria();
      $c->add(TblblogcategoryPeer::CAT_BLOG, $blogId);
      $c->add(TblblogcategoryPeer::CAT_PATH, $regString, Criteria::CUSTOM);
      $tblblogcategory = TblblogcategoryPeer::doSelect($c);
    }
    foreach($tblblogcategory as $tblblogcat) {
      $catParent = $tblblogcat->getCatParent();
      $catPath = $tblblogcat->getCatPath();
      $catName = $tblblogcat->getCatName();
      $catType = $tblblogcat->getCatType();
      $catConfig = $tblblogcat->getCatConfig();
      $catOrder = $tblblogcat->getCatOrder();
      $catPublic = $tblblogcat->getCatPublic();
      $catBase = $tblblogcat->getCatBase();

      //insert a new row
      $tblcat = new Tblblogcategory();
      $tblcat->setCatBlog($newBlogId);
      $tblcat->setCatName($catName);
      $tblcat->setCatParent($catParent);
      $tblcat->setCatPath($catPath);
      $tblcat->setCatType($catType);
      $tblcat->setCatConfig($catConfig);
      $tblcat->setCatOrder($catOrder);
      $tblcat->setCatPublic($catPublic);
      $tblcat->setCatBase($catBase);
      $tblcat->save();

      $maxCatId = $tblcat->getCatId();
      $copy[$tblblogcat->getCatId()] = $maxCatId;
    }

    //update again path
    $c = new Criteria();
    $c->add(TblblogcategoryPeer::CAT_BLOG,$newBlogId);
    $tblblogcat = TblblogcategoryPeer::doSelect($c);
    foreach($tblblogcat as $cat) {
      $path = $cat->getCatPath();
      $paths = explode(',',$path);
      $str = '';
      foreach($paths as $p) {
        if(array_key_exists($p,$copy)) {
          $str .= $copy[$p].',';
        }
      }
      $str = substr($str,0,-1);
      $cat->setCatPath($str);
      if($cat->getCatParent() != -1) {
        $parent = $cat->getCatParent();
        if(array_key_exists($parent,$copy)) {
          $parent = $copy[$parent];
        } else {
          $parent = -1;
        }
        $cat->setCatParent($parent);
      }
      $cat->save();
    }
    $this->catcopy = $copy;
  }

  public function copyData($blogFrom,$blogTo,$bg,$banner) {
    $pathTo = blogStore::getBlogFolder(true, $blogTo).'/layout';
    $pathFrom = blogStore::getBlogFolder(true, $blogFrom).'/layout/';
    if(file_exists($pathFrom.$bg)) {
      copy($pathFrom.$bg,$pathTo.'/'.$bg);
    }
    if(file_exists($pathFrom.$banner)) {
      copy($pathFrom.$banner,$pathTo.'/'.$banner);
    }
  }

  public function executeJoin() {
    $this->tblbloguser = TblbloguserPeer::retrieveByPK(blogStore::$blogId,blogStore::$userId);
    $this->forward404If($this->tblbloguser, 'Bạn đã gia nhập trang này rồi');
    $this->urlBack = $this->getRequest()->getReferer();
    $this->joined = 0;
    if($this->getRequestParameter('save') == 1) {
      $this->tblbloguser = new Tblbloguser();
      $this->tblbloguser->setUsBlog(blogStore::$blogId);
      $this->tblbloguser->setUsUser(blogStore::$userId);
      $this->tblbloguser->setUsLastvisit(date("Y-m-d H:i:s"));
      $this->tblbloguser->setUsJoindate(date("Y-m-d H:i:s"));

      //get email fullname nickname
      $tbluser = TbluserPeer::retrieveByPK(blogStore::$userId);
      $email = $tbluser->getUsEmail();
      $fullname = $tbluser->getUsFullname();
      $nickname = $tbluser->getUsUsername();
      $avatar = $tbluser->getUsAvatar();
      $this->role = $tbluser->getUsChecked()? 1: 0;
      $this->tblbloguser->setUsRole($this->role);
      $this->tblbloguser->setUsEmail($email);
      $this->tblbloguser->setUsFullname($fullname);
      $this->tblbloguser->setUsNickname($nickname);
      $this->tblbloguser->setUsPicture($avatar);
      $this->tblbloguser->save();
      $this->joined = 1;
      $this->getUser()->setIsBlogMember($this->role);
    }
  }

  public function executeContact()
  {
    $title = 'Trao đổi về trang web "'.blogStore::$blog->getBlTitle().'"';
    $title = str_replace('.', '%2E', urlencode($title));
    $this->ret = '/message/mailbox?type=compose&us_to='.blogStore::$blog->getBlUser().'&title='.$title;
    if ($this->getUser()->isAuthenticated()) $this->redirect($this->ret);
  } 
    
  public function executeFaq() {
  }
}
