Uploading Images

April 11, 2009

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>

template helpers

March 16, 2009

paths to the project directories

<?=$this->config->resource['img']?>
<?=$this->config->resource['css']?>
<?=$this->config->resource['js']?>

helpers

makelink()
Creates an absolute url to a specified action in the site

<?=$this->MakeLink($controller, $function, $params)?>

<?=$this->MakeLink('signup')?>
=> http://westendvip.com/signup

<?=$this->MakeLink('offer', 'search', 'q=Good Offers')?>
=> http://westendvip.com/offer/search.html?q=Good Offers

PrintMessages()
Prints out all the messages in the session

<?=$this->session->PrintMessages($list_tag='', $list_css='', $item_tag='', $item_css)?>

<?=$this->session->PrintErrors('ul', 'list', 'li', 'item')?>
=> <ul class='list'><li class='item'>Message appears here</li></ul>

LoadComponent
If you have a fragment to load into a page use LoadComponent() – you don’t
need the .php extension

<? $this->LoadComponent($component, $param1, $param2, $param3); ?>

<? $this->LoadComponent('PageFooter'); ?>

Recent Changes

November 17, 2008

There are two new classes that deal with file uploads they are built to mimic a domain object called FileUpload, but also handle the saving and managing of files and records corresponding the file info. Which can then be linked to objects that have files.

So from now on when you get a file it’s an object and you access it’s location by calling its name method.

$file = new FileUpload();
$file->SetFromRequest($_FILES);
$file->SetUser(new User());
$file->Save();

The reason for these changes is to a) make file uploading more simple! and b) to make the validating of the file upload more accurate.
Read the rest of this entry »

Widget Support

July 30, 2008

Read the rest of this entry »

Create A Simple Page Yourself

July 28, 2008

Read the rest of this entry »

Dynamic CSS

July 28, 2008

Read the rest of this entry »

Your First Widget

July 28, 2008

Read the rest of this entry »

Mapper Classes / Code Generator

July 25, 2008

Read the rest of this entry »

The Site Configuration File

July 24, 2008

Read the rest of this entry »

Database Tables / Naming Conventions

July 24, 2008

Read the rest of this entry »


Follow

Get every new post delivered to your Inbox.