<?php

class blogStore extends commonData {

  public static $blog;                 // Store blog info
  public static $tblblogpoll;          // Store blogpoll record
  public static $blogName = '';
  public static $blogId = 0;
  public static $adminName = '';
  public static $moduleConfig;
  public static $userId = 0;
  public static $catTree;
  public static $isRoute = false;      // Category tree of blog
  public static $cache = null;

  public static function getCache() {
    if (self::$cache) return self::$cache;
    self::$cache = sfMemcacheCache::getInstance('blogs');
    return self::$cache;
  }

  public static function resetCache() {
    self::getCache()->remove(self::$blogName, 'blogs');
    sfLoader::loadHelpers('tvtl', 'block');
    cache_include_reset();
  }

  public static function init() {
    parent::initData();
    $cache = self::getCache();
    $cacheInfo = $cache->getWithQueue(self::$blogName, 'blogs');
    if ($cacheInfo === null) {
      self::$blog = TblblogPeer::getActiveBlogByName(self::$blogName);
      self::$blogId = self::$blog->getBlId();
      self::$adminName = TbluserPeer::retrieveByPK(self::$blog->getBlUser())->getUsFullName();
      self::$moduleConfig = sfYaml::load(self::$blog->getBlModuleConfig());
      self::$catTree = new categoryTree();
      self::$tblblogpoll = TblblogpollPeer::getActivePoll(self::$blogId);

      $cache->set(self::$blogName, 'blogs', array(self::$blog, self::$blogId, self::$adminName, self::$moduleConfig, self::$catTree, self::$tblblogpoll), 86400);
      self::checkCacheJcategory();
    } else {
      list(self::$blog, self::$blogId, self::$adminName, self::$moduleConfig, self::$catTree, self::$tblblogpoll) = $cacheInfo;
    }

    $bl_host = self::$blog->getBlHost();
    if ($bl_host != null && $bl_host != sfContext::getInstance()->getRequest()->getHost()) {
      $uri = preg_replace('@^/'.self::$blogName.'@', '', $_SERVER["REQUEST_URI"]);
      header('location: http://'.$bl_host.$uri);
      exit();
    }
    $user = sfContext::getInstance()->getUser();
    self::$userId = $user->getUserId();
    sfDatabaseOnlineUser::getInstance()->addUser($user);
  }

  public static function isAdministator() {
    return sfContext::getInstance()->getUser()->isAdministrator() || self::$blog->getBlUser() == self::$userId;
  }

  public static function getUserStatus() {
    if (self::isAdministator()) return '_admin';
    if (sfContext::getInstance()->getUser()->isBlogMember()) return '_member';
    if (sfContext::getInstance()->getUser()->isAuthenticated()) return '_user';
    return '';
  }

  /**
   * @param int $cat_id: id of category
   * @return 1 if current user can post new entry in $cat_id category, 2 if user canPost but need to login
   */
  public static function canPost($cat_id = null) {
    if ($cat_id === null) $cat_id = self::getRequestCatId();
    $catItem = self::$catTree->getCatItem($cat_id);
    if (!$catItem || $catItem->isRootBranch()) return false;
    switch ($catItem->public) {
      case -1:
        return false;
      case 0:
      case 1:
        return self::isAdministator();
      case 2:
        return self::isAdministator() || sfContext::getInstance()->getUser()->isBlogMember() || self::getBlogStyle() < 0;
      case 3:
        return sfContext::getInstance()->getUser()->isAuthenticated();
    }
  }

  public static function canComment($cat_id = null) {
    if ($cat_id === null) $cat_id = self::getRequestCatId();
    $catItem = self::$catTree->getCatItem($cat_id);
    if (!$catItem) return false;
    switch ($catItem->public) {
      case -1:    //no post
      case 1:     //admin post, no comment
        return false;
      case 0:     //admin post, member comment
      case 2:     //member post and comment
        return self::isAdministator() || sfContext::getInstance()->getUser()->isBlogMember() || self::getBlogStyle() < 0;
      case 3:     //all user can post and comment
        return sfContext::getInstance()->getUser()->isAuthenticated();
    }
    return false;
  }

  public static function canMod($cat_id = null) {
    if ($cat_id === null) $cat_id = self::getRequestCatId();
    if (self::isAdministator()) return true;
    $managecat = sfContext::getInstance()->getUser()->getManageCat();
    $listcat = explode(',', $managecat);
    return in_array($cat_id, $listcat);
  }

  public static function getRequestCatId() {
    $sf_request = sfContext::getInstance()->getRequest();
    $cat_id = $sf_request->getParameter('cat_id');
    $catItem = self::$catTree->getCatItem($cat_id);
    if (!$catItem || $catItem->mod != sfContext::getInstance()->getModuleName()) {
      $sf_request->setError('message404', $catItem? 'Thư mục không hợp lệ': 'Thư mục không tồn tại');
      throw new sfError404Exception();
    }
    return $cat_id;
  }

  /**
   *
   * @param id of category
   * @return path way from root to this category
   */
  public static function getCategoryPath($cat_id, $prefix = '') {
    $pathLink = link_to('Gốc', '/') . ' &gt; ';
    $path = self::$catTree->flat[$cat_id]->path;
    foreach ($path as $pathItem) {
      $cat = self::$catTree->flat[$pathItem];
      $pathLink .= link_to($prefix.$cat->name, '/'.$cat->mod.'/list?cat_id='.$pathItem) . ' &gt; ';
    }
    return $pathLink;
  }

  public static function getPostLink($cat_id, $module, $title = 'Đưa % lên', $extra = '') {
    $catItem = self::$catTree->getCatItem($cat_id);
    if ($catItem == null) return 'Thư mục bị lỗi';
    $postText = str_replace('%', $catItem->getCatTypeName(), $title);
    return mm_link_need_login($postText, "/$module/create?cat_id=$cat_id".$extra);
  }

  /**
   * Get folder of blog
   * @param boolean $absolute =true for absolute folder in server, =false for folder from url
   */
  public static function getBlogFolder($absolute = true, $blogId = null) {
    if ($blogId == null) $blogId = self::$blogId;
    if ($absolute) $path = sfConfig::get('sf_upload_dir');
    else $path = sfConfig::get('app_blog_root').sfConfig::get('sf_upload_dir_name');
    return $path.'/blogs/'.($blogId<758840? '': 'blogs2/').$blogId;
  }

  public static function getJcatFileName($absolute = true) {
    $fileName = 'jcat' . date('ymdHis', strtotime(self::$blog->getBlLastUpdate())) . '.js';
    return self::getBlogFolder($absolute) .'/js/'. $fileName;
  }

  /**
   * Check whether category javascript file is exist
   * if this file does not exist, create new file
   */
  public static function checkCacheJcategory($forceCreate = false) {
    $jcatFileName = self::getJcatFileName();
    if ($forceCreate || !file_exists($jcatFileName)) {
      $filter = self::getParam('modules/listcategory/filter', '/./');
      file_put_contents($jcatFileName, 'g_category = "' . self::$catTree->getTree(null, $filter) . '"');
    }
  }

  /**
   * @return string of extra css of config interface of blog
   */
  public static function getLayoutCSS() {
    $css = '';
    $background = @self::$moduleConfig['config']['background'];
    $url = @$background['url'];
    if (isset($url)) {
      $repeat = @$background['repeat'];
      if (null==$repeat) $repeat = 'repeat';
      $fixed = @$background['fixed'];
      if (null!=$fixed) $fixed = 'fixed'; else $fixed = '';
      $url = self::getBlogFolder(false) . '/layout/' . $url;
      $css .= "#wrap1 {
      	background:transparent url($url) $repeat $fixed center top;
      }";
    };

    // get banner information
    $banner = @self::$moduleConfig['config']['banner']['url'];
    if (isset($banner)) {
      $banner = self::getBlogFolder(false) . '/layout/' . $banner;
      $color = @self::$moduleConfig['config']['banner']['color'];
      $color = dechex($color);
      $color = str_pad($color, 6,"0", STR_PAD_LEFT);
      $height = @self::$moduleConfig['config']['banner']['height'];
      if ($height==null) $height = 75;
      $css .= "#top3 {
    	  background:transparent url($banner) left top no-repeat;
    	  color: #$color;
    	  height: {$height}px;
    	}";
    } else if ($height = @self::$moduleConfig['config']['banner']['height']) {
      $css .= "#top3 {
    	  height: {$height}px;
    	}";
    }
    return $css;
  }

  public static function getSwfBanner() {
    $background = @self::$moduleConfig['config']['banner']['swfurl'];
    if (isset($background)) {
      $banner = self::$moduleConfig['config']['banner'];
      $background = self::getBlogFolder(false) . '/layout/' . $background;
      $width = $banner['width'];
      $height = $banner['height'];
      unset($banner['swfurl']);
      unset($banner['width']);
      unset($banner['height']);
      if (!isset($banner['tieude'])) {
        $banner['tieude'] = self::$blog->getBlTitle();
      }
      sfLoader::loadHelpers('tvtl');
      return flash_tag($background, $width, $height, $banner);
    } else return '';
  }

  /**
   * @param preg function in simple style *.*, user.*, *.create
   * @return preg in preg_match style
   */
  private function pregModule($preg, $module) {
    $preg = str_replace('.', '\.', $preg);
    $preg = str_replace('*', '([\w\d]+)', $preg);
    return preg_match('/^' . $preg . '$/', $module);
  }

  /**
   * @return array of left or center module
   */
  public static function getModules($modulePosition) {
    $getModule = array();
    $modules = @self::$moduleConfig['modules'];
    if (!array_key_exists('main', $modules)) $module['main'] = '';
    $currentModule = sfContext::getInstance()->getModuleName() . '.' . sfContext::getInstance()->getActionName();
    $user = sfContext::getInstance()->getUser();
    foreach ($modules as $name=>$module) {
      if (preg_match("/^$modulePosition$/", $module['pos']) && @$module['visible']!==0) {
        $visible = true;
        $hide = @$module['hide'];
        $show = @$module['show'];
        $allow = @$module['allow'];
        $deny = @$module['deny'];
        // if module is hide or show (depend on url filter)
        if ($hide != null && self::pregModule($hide, $currentModule)) $visible = false;
        if ($show != null && self::pregModule($show, $currentModule)) $visible = true;
        if ($visible) {
          // only show or hide if user has credential
          if ($allow!= null && !$user->hasCredential($allow)) $visible = false;
          if ($deny != null &&  $user->hasCredential($deny))  $visible = false;
        }
        if ($visible) $getModule[$name] = $module;
      }
    }
    return $getModule;
  }

  /**
   * Return route for blogs
   */
  public static function getNewRoute($host) {
    $host = strtolower($host);
    if (substr($host, 0, 4) == 'www.') $host = substr($host, 4);
    $baseHost = sfConfig::get('app_base_host');
    $baseLen = strlen($baseHost);
    if ($host == $baseHost) return null;
    if (substr($host, -$baseLen) == $baseHost) {
      $blogName = substr($host, 0, -$baseLen-1);
      if (preg_match('@^(blog|khachhang|d|d\d)$@', $blogName)) return null;
      return $blogName;
    }
    $memcache = self::getCache();
    $hostcode = substr(md5($host), 0, 2);
    var_dump($hostcode);
    $name = 'route'.$hostcode;
    $route = $memcache->getWithQueue($name, '');
    if (null==$route) {
      $c = new Criteria();
      $c->add(TblbloghostPeer::BH_HOSTCODE, $hostcode);
      $blogs = TblbloghostPeer::doSelect($c);
      $route = array();
      foreach ($blogs as $blog) {
        $route[$blog->getBhHost()] = $blog->getBhBlogname();
      }
      $memcache->set($name, '', $route, 0);
    }
    return @$route[$host];
  }

  public static function resetNewRoute($host) {
    $name = 'route'.substr(md5($host), 0, 2);
    self::getCache()->remove($name, '');
  }

  /**
   * @uses getParams('config1/config2/config3', 'default');
   */
  public static function getParam($params, $defaultValue = null) {
    $params = explode('/', $params);
    $ret = self::$moduleConfig;
    foreach ($params as $param) {
      $ret = @$ret[$param];
      if ($ret == null) return $defaultValue;
    }
    return $ret;
  }

  /**
   * @uses setParam('config1/config2/config3', 'value');
   */
  public static function setParam($params, $value) {
    $params = explode('/', $params);
    $n = count($params);
    $config = &self::$moduleConfig;
    for ($i = 0; $i<$n-1; $i++) {
      $config = &$config[$params[$i]];
    }
    $config[$params[$n-1]] = $value;
  }

  public static function getNewsStyle() {
    return self::getParam('config/news-display-style', 1);
  }

  public static function getDisplayStyle($index = 0) {
    $type = self::getParam('config/display-style', 1);
    if ($type == 1) $type = 'thumb';
    if ($type == 2 || $type == 'bigview') $type = ($index==0)? 'bigview': 'thumb';
    return $type;
  }

  public static function getDisplayCount($cat_type) {
    if ($cat_type == 2) {
      if (blogStore::getNewsStyle()==2) return 5;
      else return 3;
    }
    $counts = sfConfig::get('app_thumbnail_dir_count');
    return $counts[blogStore::getDisplayStyle()];
  }

  public static function getBlogStyle() {
    return self::$blog->getBlType();
  }
}
