Uploading Images

By orqi

Domain Object

class Siteimage extends Object
{
  public $tmp_name;
  public $versions = array();

  function Siteimage($id='', $user='', $size='', $type='', $name='', $label='')
  {
    $this->id = $id;
    $this->user = $user;
    $this->size = $size;
    $this->type = $type;
    $this->name = $name;
    $this->label = $label;
  }

  function GetTmpName() { return $this->tmp_name; }

  function GetName()
  {
    if ($this->isGhost()) $this->PopulateMe();
    if (empty($this->name))
    {
      list($object_type, $extension) = explode('/', $this->type);
      $this->name = '/' . CodeGenerator::GetCode() . '.' . $extension;
    }
    return $this->name;
  }

  function SetFromRequest($file='')
  {
    $this->tmp_name = $file['tmp_name'];
    $this->type = $file['type'];
    $this->size = $file['size'];
  }

  function SaveFile()
  {
    $config = Config::GetInstance();
    $file_path = $config->resource['path'] . $this->GetName();

    if (move_uploaded_file($this->GetTmpName(), $file_path))
    {
      chmod($file_path, 0777);
      return true;
    }
    else
    {
      $this->session = new Session();
      $this->error = new Message('fileupload', "I think there's something wrong saving the file to the folder.");
      return false;
    }
  }

  function DeleteFile()
  {
    $config = Config::GetInstance();
    $this->DeleteVersions();
    unlink($config->resource['path'] . $this->GetName());
    return true;
  }

  function DeleteVersions()
  {
    $config = Config::GetInstance();
    foreach ($config->image as $version => $version_details)
    {
      $components = explode('/', $this->GetName());
      $components[count($components)-1] = $version . "_" . $components[count($components)-1];
      $separator = '';
      foreach ($components as $component)
      {
        $this->versions[$version] .= $separator . $component;
        $separator = "/";
      }

      if (file_exists($config->resource['path'] . $this->versions[$version]))
      {
        unlink($config->resource['path'] . $this->versions[$version]);
      }
    }
  }
}

Validator

class SiteimageValidator extends BaseSiteimageValidator
{
	function SiteimageValidator($post='', $files='') { $this->Initialise($post, $files); }

	function Populate($post='', $files='')
	{
		if (is_a($post, 'Siteimage'))
		{
			$this->id = $post->GetId();
			$this->user = $post->GetUser()->GetId();
			$this->name = $post->GetName();
			$this->label = $post->GetLabel();
		}
		else
		{
			$this->id = $post['id'];
			$this->user = $post['user'];
			$this->name = $files['name'];
			$this->label = $post['label'];
		}
	}

	function Save()
	{
		$siteimage = new Siteimage();
		$siteimage = (empty($this->id)) ? new Siteimage() : $siteimage->GetMapper()->Find(new SiteImage($this->id));
		if ($this->name['error'] != UPLOAD_ERR_NO_FILE) $siteimage->SetFromRequest($this->name);
		$siteimage->SetUser(new User($this->user));
		$siteimage->SetLabel($this->label);
		return ($siteimage->Save()) ? $siteimage : false;
	}

	function isValid()
	{
		$this->errors = array();

		if (empty($this->label)) $this->errors[] = new Message('label', "You should type a unique label for the image.");
		else if (!$this->IsValidAlphanumeric($this->label)) $this->errors[] = new Message('label', "You can only have hyphens, spaces, letters and numbers in this field.");
		else
		{
			$siteimage_mapper = new Siteimages();
			$siteimage = $siteimage_mapper->FindByLabel($this->label);

			if (is_a($siteimage, 'Siteimage') && $siteimage->GetId() != $this->id) $this->errors[] = new Message('label', "Sorry, but that label is already in use for another image.");
		}

		if (($this->name['error'] != UPLOAD_ERR_NO_FILE && !empty($this->id)) || empty($this->id))
		{
			$file_error_message = $this->ValidateFile($this->name, array("image/jpeg", "image/jpg", "image/gif", "image/png"));
			if ((string)$file_error_message == "File type is not correct.") $this->errors[] = new Message('name', "You can only upload GIFs, PNGs or JPEGs. ");
			else if ($file_error_message !== true) $this->errors[] = new Message('name', $file_error_message);
		}
		if (!$this->IsValidInt($this->user)) $this->errors[] = new Message('user', "Can't find a user to add the image with.");

		return empty($this->errors);
	}
}

Mapper

class Siteimages extends Mapper
{
  function Save(&$object)
  {
    $action_text = ($object->isNew()) ? "insert into " : "update ";
    if (!$object->isNew()) $condition = "where id=" . $object->GetId();

    if ($object->GetTmpName() != "")
    {
      if (!$object->isNew())
      {
        $old_file = $object->GetName();
        $object->SetName();
      }
      if (!$object->SaveFile())
      {
        $session = new Session();
        $session->AddMessage(new Message('save', "There was a problem saving the file. "));
        return false;
      }
    }

    $sql_string = "
      $action_text  siteimages
      set        user    =" . $object->GetUser()->GetId() . ",
              name    ='" . $object->GetName() . "',
              type    ='" . $object->GetType() . "',
              size    ='" . $object->GetSize() . "',
              label    ='" . $object->GetLabel() . "'
      $condition
    ";

    if ($this->dao->ExecuteQuery($sql_string))
    {
      if (!$object->isNew() && $object->GetTmpName() != "")
      {
        $object->SetName($old_file);
        $object->DeleteFile();
      }
      if ($object->isNew()) $object->SetId(mysql_insert_id($this->dao->conn));
      return true;
    }
    else
    {
      $object->DeleteFile();
      return false;
    }
  }
}

Controller

class SiteimageController extends Controller
{
  function Input()
  {
    $siteimage_mapper = new Siteimages();
    $this->siteimage = $siteimage_mapper->Find(new Siteimage($this->get['id']));

    if (empty($this->post))
    {
      $this->form = new SiteimageValidator($this->siteimage);
      if (!is_a($this->siteimage, 'Siteimage')) $this->form->SetUser($this->session->user->GetId());
    }
    else
    {
      $this->form = new SiteimageValidator($this->post, $this->files);

      if ($this->form->isValid())
      {
        $siteimage = $this->form->Save();
        if ($siteimage instanceof Siteimage)
        {
          $this->session->AddMessage(new Message("success", "Your picture was saved successfully. "));
          $this->Redirect($this->MakeLink('siteimage', 'all'));
        }
        else
        {
          $this->session->AddMessage(new Message('database_error', "Couldn't save to the database. "));
        }
      }
    }

    $this->LoadTemplate("FormSiteimage");
  }
}

Template

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <? $this->LoadComponent('HeadTag'); ?>
  <body>
    <? $this->LoadComponent('AdminHeader'); ?>
    <div class="pod twoCol">
      <h2>Site Image Upload Form</h2>
      <div>
        <br>
        <?=$this->session->PrintMessages()?>
        <?=$this->form->PrintError('user')?>

        <form method='post' action='' enctype="multipart/form-data">
          <input type="hidden" class="hidden" name="MAX_FILE_SIZE" value="300000" />
          <input type='hidden' class="hidden" name='id' value='<?=$this->form->GetId()?>' />
          <input type='hidden' class="hidden" name='user' value='<?=$this->form->GetUser()?>' />

          <label for='label'>Label</label>
          <input type='text' name='label' value="<?=$this->form->GetLabel()?>" id='label' />
          <?=$this->form->PrintError('label')?>
          <br>

          <label for='name'>Image Location</label>
          <input type='file' name='name' value="" id='name' />
          <p>Please choose an image file to upload.</p>
          <?=$this->form->PrintError('name')?>
          <br>

          <? if ($this->siteimage instanceof Siteimage) { ?>
            <label>Current Image</label>
            <img src="<?=$this->siteimage->GetVersion('thumbnail')?>" />
            <br>
            <br>
          <? } ?>
          <label></label>
          <input type='submit' name='submit' value='Save' class='submit' />
        </form>
      </div>
    </div>
    <? $this->LoadComponent('PageFooter'); ?>
  </body>
</html>

Leave a Reply