06.14
php
digitalspaghetti
Note
Version 1.1 of my improved upload behaviour
Version 1.1 of my improved upload behaviour
- <?php
- /**
- * Improved Upload Behaviour
- * This behaviour is based on Chris Partridge's upload behaviour (http://bin.cakephp.org/saved/17539)
- * @author Tane Piper (digitalspaghetti@gmail.com)
- * @link http://www.digitalspaghetti.me.uk
- * @filesource http://bakery.cakephp.org/articles/view/improved-upload-behaviour-with-thumbnails-and-name-correction
- * @version 1.1
- * @modifiedby $LastChangedBy:$
- * @lastmodified $Date:$
- * @svn $Id:$
- *
- * Useage:
- * 1) Download this behaviour and place it in your models/behaviours/upload.php
- * 2) If you require thumbnails for image generation, download Nate's phpThumb Component (http://bakery.cakephp.org/articles/view/phpthumb-component)
- * 3) Insert the following SQL into your database. This is a basic model you can expand on:
- * CREATE TABLE `images` (
- * `id` int(8) unsigned NOT NULL auto_increment,
- * `filename` varchar(255) default NULL,
- * `dir` varchar(255) default NULL,
- * `mimetype` varchar(255) NULL,
- * `filesize` int(11) unsigned default NULL,
- * `created` datetime default NULL,
- * `modified` datetime default NULL,
- * PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
- * 4) In your model that you want to have the upload behavior work, place the below code. This example is for an Image model:
- *
- * var $actsAs = array('Upload' => array(
- * 'filename' => array(
- * 'dir' => 'files/images',
- * 'overwrite_existing' => false,
- * 'create_directory' => false,
- * 'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/gif', 'image/png'),
- * 'allowed_ext' => array('.jpg', '.jpeg', '.png', '.gif'),
- * 'thumbsizes' => array(
- * 'small' => array('width'=>100, 'height'=>100),
- * 'medium'=> array('width'=>220, 'height'=>220),
- * 'large' => array('width'=>800, 'height'=>600)
- * )
- * )
- * )
- * );
- * The above code will save the uploaded file's name in the 'filename' field in database,
- * it will not overwrite existing files, instead it will create a random filename if
- * it already exists.
- * Allowed Mimetypes and extentions should be pretty explanitory
- * For thumbnails, when the file is uploaded, it will create 3 thumbnail sizes and prepend the name
- * to the thumbfiles (i.e. image_001.jpg will produced thumb.small.image_001.jpg, thumb.medium.image_001.jpg, etc)
- *
- * 5) Create your upload view, make sure it's a multipart/form-data form, and the filename field is of type $form->file
- * 6) Make sure your directory is at least CHMOD 775, also check your php.ini MAX_FILE_SIZE is enough to support the filesizes you are uploading
- *
- * Version Details
- *
- * 1.1
- * + Improved Image scaling code
- * + Fixed check to see if file exists and rename file to unique name
- * + Improved model actsAs to allow more thumbnail sizes
- *
- * 1.0
- * + Initial release with thumbnail code.
- */
- uses('folder');
- uses('file');
- class UploadBehavior extends ModelBehavior {
- 'overwrite_existing' => false,
- 'create_directory' => true,
- );
- "/\s/", # Whitespace
- "/\&/", # Ampersand
- "/\+/" # Plus
- );
- "_", # Whitespace
- "and", # Ampersand
- "plus" # Plus
- );
- //$this->File = &new File;
- $this->Folder = &new Folder;
- foreach($config as $field => $options) {
- // Check if given field exists
- if(!$model->hasField($field)) {
- }
- // Merge given options with defaults
- // Generate temporary directory if none provided
- $options['dir'] = 'img' . DS . 'uploads' . DS . $model->name;
- }
- // Check if directory exists and create it if required
- if($options['create_directory'] && !$this->Folder->mkdirr($options['dir'])) {
- }
- }
- // Check if directory is writable
- }
- // Check that the given directory does not have a DS on the end
- }
- }
- $this->__fields = $config;
- }
- function beforeSave(&$model)
- {
- $filtered_filename = '';
- $random_filename = false;
- foreach($this->__fields as $field=>$options) {
- // Check for upload
- continue;
- }
- // Check error
- if($model->data[$model->name][$field]['error'] > 0) {
- continue;
- }
- // Fix name
- $filename = preg_replace($this->patterns,$this->replacements,$model->data[$model->name][$field]['name']);
- for ($i=0;$i<strlen($filename);$i++) {
- $filtered_filename .= $current_char;
- }
- }
- $model->data[$model->name][$field]['name'] = $filtered_filename;
- // Check mime
- continue;
- }
- // Check extensions
- $matches = 0;
- foreach($options['allowed_ext'] as $extension) {
- $matches++;
- $keepext = $extension;
- }
- }
- if($matches == 0) {
- continue;
- }
- }
- // Create final save path
- $saveAs = $options['dir'] . DS . $model->data[$model->name][$field]['name'];
- // Check if file exists
- $saveAs = $options['dir'] . DS . $model->data[$model->name][$field]['name'];
- }
- }
- // Attempt to move uploaded file
- continue;
- }
- // Create thumbnail of uploaded image
- // This is hard-coded to only support JPEG + PNG at this time
- // Code unable to handle other formats
- {
- foreach ($options['thumbsizes'] as $key => $value) :
- $this->createthumb($saveAs, $options['dir'] . DS . 'thumb.' . $key . '.' . $model->data[$model->name][$field]['name'], $value['width'], $value['height']);
- endforeach;
- }
- // Update model data
- $model->data[$model->name]['dir'] = $options['dir'];
- $model->data[$model->name]['mimetype'] = $model->data[$model->name][$field]['type'];
- $model->data[$model->name]['filesize'] = $model->data[$model->name][$field]['size'];
- $model->data[$model->name][$field] = $model->data[$model->name][$field]['name'];
- }
- }
- }
- // FIXME: This currently does not delete images :(
- function beforeDelete(&$model)
- {
- {
- $model->read(null, $model->id);
- {
- foreach($this->__fields as $field=>$options)
- {
- $file = $model->data[$model->name][$field];
- {
- $dir=$options['dir'];
- $folder = &new Folder($dir);
- return false;
- }
- }
- }
- }
- return true;
- }
- // Function to create thumbnail image
- // This requires Nate Constant's thumbnail generator for PHPThumb
- // http://bakery.cakephp.org/articles/view/phpthumb-component
- function createthumb($name, $filename, $new_w, $new_h)
- {
- loadComponent('thumb');
- {
- $src_img = imagecreatefromjpeg($name);
- }
- {
- $src_img = imagecreatefrompng($name);
- }
- $old_x = imagesx($src_img);
- $old_y = imagesy($src_img);
- if ($old_x >= $old_y)
- {
- $thumb_w = $new_w;
- $ratio = $old_y / $old_x;
- $thumb_h = $ratio * $new_w;
- } else if ($old_x < $old_y) {
- $thumb_h = $new_h;
- $ratio = $old_x / $old_y;
- $thumb_w = $ratio * $new_h;
- }
- $dst_img = imagecreatetruecolor($thumb_w, $thumb_h);
- imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
- {
- imagepng($dst_img, $filename);
- } else {
- imagejpeg($dst_img, $filename);
- }
- imagedestroy($dst_img);
- imagedestroy($src_img);
- }
- }
- ?>
Parsed in 0.426 seconds, using GeSHi 1.0.7.14