<?php
require_once DTO . 'ImageDto.php';
final class Image extends Action {
  private $dto;
  public function __construct() {
    $this->checkAccess();
    $this->dto = new ImageDto();
  }
  protected function getDto() {
    return $this->dto;
  }
  public function index() {
    return new forward();
  }
  public function upload() {
    if (!empty($this->dto->currPhoto) && file_exists(IMAGES . $this->dto->currPhoto)) {
      unlink(IMAGES . $this->dto->currPhoto);
    }
    $tmp = $_FILES['photo']['tmp_name'];
    $file = md5_file($tmp) . '.' . pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
    if (is_uploaded_file($tmp)) {
      switch (exif_imagetype($tmp)) {
        case IMAGETYPE_JPEG:
        case IMAGETYPE_PNG:
        case IMAGETYPE_GIF:
          if (move_uploaded_file($tmp, IMAGES . $file)) {
            chmod(IMAGES . $file, 0777);
            $this->dto->currPhoto = $file;
          }
          break;
        default:
          $this->setError('画像ファイルを選択してください。');
      }
    }
    return new forward();
  }
  public function remove() {
    header('Content-Type: application/json; charset=utf-8');
    if (!empty($this->dto->currPhoto) && file_exists(IMAGES . $this->dto->currPhoto)) {
      unlink(IMAGES . $this->dto->currPhoto);
    }
    echo '{"result":"OK"}';
    return new Direct();
  }
}
// EOF.
