Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "file"

sfValidatorFileImage : a simple validator for image file (symfony 1.2)

Description :

This is a class for symfony 1.2 for images. It extends the class sfValidatorFile.

<?php
 
/**
 * sfValidatorFileImage
 *
 * Original validator for symfony 1.0 : http://snippets.symfony-project.org/snippet/259
 *
 * @package    symfony
 * @subpackage validator
 * @author     Yoann Brieux <yoann |dot¤ brieux #at] gmail ~dot} com>
 * @version    0.1
 */
class sfValidatorFileImage extends sfValidatorFile
{
  /**
   * @param array $options   An array of options
   * @param array $messages  An array of error messages
   *
   * @see sfValidatorFile
   */
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);
 
    $this->addMessage('invalid_image', '%value% is an incorrect image file.');
    $this->addMessage('max_height', '"%value%" height is too long (%max_height% pixels max).');
    $this->addMessage('min_height', '"%value%" height is too short (%min_height% pixels min).');
    $this->addMessage('max_width', '"%value%" width is too long (%max_width% pixels max).');
    $this->addMessage('min_width', '"%value%" width is too short (%min_width% pixels min).');
 
    $this->addOption('max_height');
    $this->addOption('min_height');
    $this->addOption('max_width');
    $this->addOption('min_width');    
    $this->addOption('is_only_image',false);    
  }
 
  /**
   * @see sfValidatorFile
   */
  protected function doClean($value)
  {
    $clean = parent::doClean($value);
 
    $size = @getimagesize($clean->getTempName());
 
    if (!$size && !$this->getOption('is_only_image')) 
    {
        return $clean;
    }
 
    if (!$size){    
      throw new sfValidatorError($this, 'invalid_image', array('value' => $value['name']));
    }
 
    list($width, $height) = $size;
 
    if($this->getOption('max_height') < $height){
        throw new sfValidatorError($this, 'max_height', array('value' => $value['name'], 'max_height' => $this->getOption('max_height')));
    }
 
    if($this->getOption('min_height') > $height){
        throw new sfValidatorError($this, 'min_height', array('value' => $value['name'], 'min_height' => $this->getOption('min_height')));
    }
 
    if($this->getOption('max_width') < $width){
        throw new sfValidatorError($this, 'max_width', array('value' => $value['name'], 'max_width' => $this->getOption('max_width')));
    }
 
    if($this->getOption('min_width') > $width){
        throw new sfValidatorError($this, 'min_width', array('value' => $value['name'], 'min_width' => $this->getOption('min_width')));
    }
 
    return $clean;
  }
}
 

How to use it?

In the your form library :

    $this->validatorSchema['field'] = new sfValidatorFileImage(array(
        'required'                          =>  false,
        'path'                              =>  sfConfig::get('sf_upload_dir').'/news/',
        'max_height'                        =>  238,
        'min_height'                        =>  238,
        'max_width'                         =>  270,
        'min_width'                         =>  270,
        'mime_types'                        =>  array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif','application/x-shockwave-flash')
        )
    );
 

If the variable "is_only_image" is true and function "getimagesize" return false (is not a valid image for example), this validator cause an sfValidatorError exception with the message "[your file] is an incorrect image file."

by Yoann Brieux on 2009-06-15, tagged 12  file  files  image  images  symfony  validator  validators 

admin Generator and Thumnail generation in file uploads with symfony 1.2

Hello to the desperate,

As you might have probably already mentioned, the old way, how to produce thumbnails stopped working. This is because of the brand new admin generator, using an all new model based on forms, which doesn't support the old methods.

this is the new way, how to get it working again:

put this into your generator.yml file (take care for the correct identation, do not use tabs!!):

      edit:
        title: Photo uploads 
        fields:
          foto:
            type:       admin_input_file_tag
            upload_dir: /uploads/pictures/
            params:     include_link=/uploads/pictures/ include_remove=true
 

and then enhance the file lib/form/YourclassForm.php with the following method:

  protected function processUploadedFile($field, $filename = null, $values = null) {
    // first of all do what this is supposed to do
    $fn = parent::processUploadedFile($field, $filename, $values);
    // and now we can finally start doing additional stuff after the upload *hurra*
    if ($fn != "") {
        // if there is a file, that has been saved
        // multidimensional array that defines the sub-directories to store the thumbnails in
        $thumbnails[]=array('dir' => '90x90', 'width' => 90, 'height' => 90);
        $thumbnails[]=array('dir' => '200x200', 'width' => 200, 'height' => 200);
 
        foreach ($thumbnails as $thumbParam)
        {
          $currentFile = sfConfig::get('sf_upload_dir').'/pictures/'.$thumbParam['dir'].'/'. $fn;
          if (is_file($currentFile)) unlink($currentFile);
        }
        foreach ($thumbnails as $thumbParam)
        {
            $thumbnail = new sfThumbnail($thumbParam['width'], $thumbParam['height'],true,false); 
            $thumbnail->loadFile(sfConfig::get('sf_upload_dir')."/pictures/".$fn);
            $thumbnail->save(sfConfig::get('sf_upload_dir').'/pictures/'.$thumbParam['dir'].'/'.$fn, 'image/jpeg');
        }
    }
    // do not forget to return the value of the parent-function, otherwise it stops working
    return $fn;
  }  
 

Hope, you can use that snippet!

lg Christoph

by Christoph Christ on 2009-05-07, tagged admin  file  generator  sfthumbnail  symfony  uploads 
(2 comments)

How to send/download a temporary file and delete that file after download complete

The magic method to delete the file at the end of the script is "register_shutdown_function('unlink', $file)".

public function executeExport(){
    $somecontent = "Some content\n";
    //create temporary file
    $file = tempnam(sfConfig::get(''), 'FOO');
 
    // Write $somecontent to our temporary file
    fwrite($handle, $somecontent);
 
    //send file as attachement 
    $this->getResponse()->setHttpHeader("Content-type", "application/octet-stream");
    $this->getResponse()->setHttpHeader("Content-Disposition", "attachment; filename=\"export.csv\"");
    $this->getResponse()->setContent(file_get_contents($file));
 
    //delete temporary file
    register_shutdown_function('unlink', $file);
 
    return sfView::NONE;
}
 
by Cristian Baciu on 2009-02-23, tagged delete  download  export  file  temporary 
(1 comment)