<?php

class sfMyWebRequest extends sfWebRequest
{
  public function getPathInfo()
  {
    $pathInfo = parent::getPathInfo();
    $blogName = blogStore::getNewRoute($this->getHost());
    var_dump($this->getHost());
    if ($blogName != null) {
      blogStore::$blogName = $blogName;
      blogStore::$isRoute = true;
    } else {
      if (preg_match('/^\/([A-Za-z0-9_-]+)/', $pathInfo, $blogName)) {
        blogStore::$blogName = $blogName[1];
        $pathInfo = preg_replace('/^\/[A-Za-z0-9_-]+/', '', $pathInfo);
        if (!$pathInfo) $pathInfo = '/';
      } else {
        header('location: http://' . $this->getHost() . '/main/');
        exit();
      }
    }
    return $pathInfo;
  }

  public function removeAllError() {
    $this->errors = array();
  }

  public function GetFileFromRequest($allowNoFile, &$result, $fileIndex = 0) {
    if ($this->hasErrors()) throw new Exception("Quá trình upload có lỗi");
    if (!$this->hasFiles() && $allowNoFile) return false;

    $uploadedFiles = $this->getFileNames();
    $uploaded = $uploadedFiles[$fileIndex];
    $fileName = $this->getFileName($uploaded);
    $fileSize = $this->getFileSize($uploaded);
    $fileError = $this->hasFileError($uploaded);
    $fileErrorNum = $this->getFileError($uploaded);

    if ($fileError) {
      switch ($fileErrorNum) {
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
          throw new Exception('Kích thước file quá lớn');
        case UPLOAD_ERR_PARTIAL:
          throw new Exception('Lỗi đường truyền, đề nghị upload lại');
        case UPLOAD_ERR_NO_FILE:
          if ($allowNoFile) return false;
          else throw new Exception('Bạn phải chọn file để đưa lên');
        default:
          throw new Exception('Lỗi không xác định');
      }
    }
    if ($fileSize == 0) throw new Exception('File không có nội dung');

    $fileName = urldecode($fileName);
    $fileName = str_replace(' ', '_', $fileName);
    $fileName = myUtility::vietDecode($fileName);
    $fileName = myUtility::getSafeFileName($fileName);

    $result->uploaded = $uploaded;
    $result->fileName = $fileName;
    $result->fileSize = $fileSize;

    return true;
  }

  function CopyTempFile($uploaded, $tempName) {
    $tempFile = sfConfig::get('sf_upload_dir').'/'.sfConfig::get('app_temp_dir').'/'.$tempName;
    $this->moveFile($uploaded, $tempFile);
    return $tempFile;
  }
}
