public function setup()
 {
     parent::setup();
     unset($this->widgetSchema['type']);
     unset($this->widgetSchema['lft']);
     unset($this->widgetSchema['rgt']);
     unset($this->widgetSchema['level']);
     unset($this->validatorSchema['type']);
     unset($this->validatorSchema['lft']);
     unset($this->validatorSchema['rgt']);
     unset($this->validatorSchema['level']);
     $this->validatorSchema['tags'] = new sfValidatorAnd(array(new sfValidatorString(), new sfValidatorRegex(array('pattern' => '#^[^, ;]([^, ;]+[,; ] ?)*?[^, ;]+$#'))), array('required' => false));
     $directory_choices = sfFilebaseDirectoryTable::getChoices();
     $this->widgetSchema['directory'] = new sfWidgetFormTree(array('value_key' => 'id', 'choices' => $directory_choices, 'label_key' => 'filename'));
     $this->validatorSchema['directory'] = new sfValidatorTree(array('value_key' => 'id', 'label_key' => 'filename', 'choices' => $directory_choices));
     if ($this->isNew()) {
         unset($this->widgetSchema['filename']);
         unset($this->validatorSchema['filename']);
         $this->widgetSchema['hash'] = new sfWidgetFormInputSWFUpload(array('require_yui' => true, 'custom_javascripts' => array(public_path('/sfFilebasePlugin/js/fileupload.js'))));
         $this->validatorSchema['hash'] = $this->filebase->getUploadedFilesManager()->createFileUploadValidator(array('path' => $this->filebase->getPathname(), 'allow_overwrite' => true, 'required' => true));
         $this->widgetSchema['directory']->setDefault($directory_choices[0]['id']);
     } else {
         unset($this->widgetSchema['hash']);
         unset($this->validatorSchema['hash']);
         $this->validatorSchema['filename'] = new sfValidatorString();
         $p = $this->getObject()->getNode()->getParent();
         $parent_id = $p instanceof sfFilebaseDirectory ? $p->getId() : 0;
         $this->widgetSchema['directory']->setDefault($parent_id);
     }
     $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'checkUpload'))));
 }
 /**
  * Creates the cache directory on demand
  *
  * @param sfFilebasePluginDirectory | string: The pathname of the cache directory.
  * @return sfFilebasePluginDirectory $cache_directory
  */
 public function initCacheDirectory($cache_directory)
 {
     $this->cacheDirectory = $this->filebase->getFilebaseFile($cache_directory);
     if (!$this->cacheDirectory->fileExists()) {
         $this->cacheDirectory = $this->filebase->mkDir($this->cacheDirectory);
     }
     return $this->cacheDirectory;
 }
예제 #3
0
 public function executeRetrieveFiles(sfWebRequest $request)
 {
     $f = sfFilebasePlugin::getInstance();
     $this->is_edit = false;
     if ($this->form instanceof sfForm) {
         $this->is_edit = true;
         $this->file_object = $this->form->getObject();
         $this->file = $this->file_object->getFile();
     } elseif ($this->sf_filebase_file instanceof sfAbstractFile) {
         $this->file_object = $this->sf_filebase_file;
         $this->file = $this->file_object->getFile();
     } else {
         return sfView::NONE;
     }
 }
예제 #4
0
 public function executeDisplay_image(sfWebRequest $request)
 {
     $id = $request->getParameter('file', null);
     $this->forward404If($id === null);
     $f = sfFilebasePlugin::getInstance();
     $file_object = Doctrine::getTable('sfFilebaseFile')->find($id);
     $file = $f->getFilebaseFile($file_object->getHash())->getThumbnail(array('width' => $request->getParameter('width', null), 'height' => $request->getParameter('height', null)));
     $this->forward404If($file === null);
     $this->setLayout(false);
     $this->getResponse()->setContentType($file->getMimeType('application/octet-stream'));
     $this->getResponse()->setHttpHeader('Content-Tranfer-Encoding', 'binary');
     $this->getResponse()->setHttpHeader('Content-Length', $file->getSize());
     //$this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename=' . $file->getFilename() . ' size=' . $file->getSize());
     $this->getResponse()->setContent($file->openFile('r+')->fileGetContents());
     return sfView::NONE;
 }
 public static function getChoices()
 {
     $table = Doctrine::getTable('sfFilebaseDirectory');
     $root = $table->getRootNode();
     $tree_object = Doctrine::getTable('sfFilebaseDirectory')->getTree();
     $tree = $tree_object->fetchTree(array('root_id' => $root->getId()));
     if (!$tree) {
         $root = new sfFilebaseDirectory();
         $root->setFilename(sfFilebasePlugin::getInstance()->getFilename());
         $root->setHash(sfFilebasePlugin::getInstance()->getHash());
         $root->save();
         $tree_object->createRoot($root);
         $tree = $tree_object->fetchTree();
     }
     return $tree;
 }
    protected function execute($arguments = array(), $options = array())
    {
        $root_directory_path = sfConfig::get('app_sf_filebase_plugin_path_name');
        if ($root_directory_path) {
            fwrite(STDOUT, "\n    Will use output directory specified in app.yml: {$root_directory_path}\n");
        } else {
            $root_directory_path = sfConfig::get('sf_upload_dir');
            if ($root_directory_path) {
                fwrite(STDOUT, "\n    No output directory specified in app.yml, will use {$root_directory_path}\n");
            } else {
                $error_message = <<<EOF
You have to specify a directory to store your uploaded files in. In apps/{your_app}/config/app.yml, write:
all:
  sf_filebase_plugin:
    path_name: /home/joshi/www/test/web/uploads/assets
EOF;
                throw new Exception($error_message);
            }
        }
        $filebase = sfFilebasePlugin::getInstance();
        if (!$filebase->fileExists() || !$filebase->isWritable()) {
            throw new Exception(sprintf('Filebase root directory %s does not exist or is write protected. Ensure that the directory exists in file system and that it is writable by the running php processes/apache users.', $filebase->getPathname()));
        }
        // initialize the database connection
        sfContext::createInstance($this->configuration);
        $databaseManager = sfContext::getInstance()->getDatabaseManager();
        $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
        $root = Doctrine::getTable('sfFilebaseDirectory')->getRootNode($options['env'], $arguments['application'], null, true);
        $tree_object = Doctrine::getTable('sfFilebaseDirectory')->getTree();
        if ($root->getRootId()) {
            fwrite(STDOUT, "\n    Root node already exists in database, nothing to do.\n");
        } else {
            try {
                $root->setFilename($filebase->getFilename());
                $root->setHash($filebase->getHash());
                $root->setApplication($arguments['application']);
                $root->setEnvironment($options['env']);
                $root->save();
                $tree_object->createRoot($root);
                fwrite(STDOUT, sprintf("\n    Creating root node %s.\n", $filebase->getPathname()));
            } catch (Exception $e) {
                throw new Exception("\n    Error creating root node in database. Check your connection parameters!\n\n{$e}\n");
            }
        }
        fwrite(STDOUT, "\n    Database initialized, you may now use the filebase backend feature.\n");
        fwrite(STDOUT, "\n");
    }
 /**
  * Configures the current validator.
  *
  * The api for sfFilebasePluginValidatorFile is derived from sfValidatorFile.
  * So there are only little changes in handling, but the return value
  * is of type sfFilebaseUploadedFile, which have a few ways to deal with
  * uploaded files, move them, create thumbnails and so on...
  *
  * There are no mime guessers, the sfFilebasePluginUploadedFilesManager
  * deals with that when you call sfFilebasePlugin::getUploadedFiles().
  *
  * There is also no path to specify, you do that later directly by calling
  * sfFilebasePluginUploadedFile::moveUploadedFile
  *
  * As a compromise, you cannot specify your own fileclass anymore, beside
  * extending sfFilebaseUploadedFile and -manager.
  *
  * Available options:
  *
  *  * max_size:             The maximum file size
  *  * mime_types:           Allowed mime types array or category (available categories: web_images)
  *  * mime_type_guessers:   An array of mime type guesser PHP callables (must return the mime type or null)
  *  * mime_categories:      An array of mime type categories (web_images is defined by default)
  *  * path:                 The path where to save the file - as used by the sfValidatedFile class (optional)
  *  * validated_file_class: Name of the class that manages the cleaned uploaded file (optional)
  *  * allow_overwrite:       If set to true, existing files will be overwritten. Otherwise, an form field error will rise (optional)
  *                          This comes only in effect, if path is set (otherwise you'd to save the file manually)
  *  * filebase              Instance of filebase, needed if you want to save the file under another location than the
  *                          symfony default filebasePlugindDirectory (web/uploads) (optional)
  *
  * Available error codes:
  *
  *  * max_size
  *  * mime_types
  *  * partial
  *  * no_tmp_dir
  *  * cant_write
  *  * extension
  *
  * @param array $options   An array of options
  * @param array $messages  An array of error messages
  *
  * @see sfValidatorFile
  * @see sfValidatorBase
  */
 protected function configure($options = array(), $messages = array())
 {
     parent::configure($options, $messages);
     unset($this->options['mime_type_guessers']);
     $this->addOption('mime_categories', array('web_images' => sfFilebasePluginUtil::$WEB_IMAGES));
     $this->addOption('allow_overwrite', false);
     $this->addOption('filebase', sfFilebasePlugin::getInstance());
     $this->setOption('validated_file_class', 'sfFilebasePluginUploadedFile');
     $this->addMessage('file_exists', 'Destinated file %file% already exists.');
     // cleanup filebase option
     $fb = $this->getOption('filebase');
     if (is_string($fb)) {
         $this->setOption('filebase', sfFilebasePlugin::getInstance($fb));
     } elseif (!$this->getOption('filebase') instanceof sfFilebasePlugin) {
         $this->setOption('filebase', sfFilebasePlugin::getInstance());
     }
     // Calculate target path
     if (!$this->getOption('path')) {
         $this->setOption('path', $this->getOption('filebase')->getPathname());
     } else {
         $this->setOption('path', $this->getOption('filebase')->getFilebaseFile($path)->getPathname());
     }
 }
 /**
  * Sets or overrides the default filebase accessible by
  * sfFilebasePlugin::getInstance() sine id argument
  * @param sfFilebasePlugin $filebase
  */
 public static function setDefault(sfFilebasePlugin $filebase)
 {
     if (!array_key_exists($filebase->getId(), self::$instances)) {
         throw new sfFilebasePluginException(sprintf('The filebase identified by %s was not properly registered.', $filebase->getId()));
     }
     self::$instances['default'] = $filebase;
 }
/**
 * helper for easily retrieve an instance of sfFilebasePlugin
 * in your view file.
 *
 * Enable the helper by typing
 *   <?php use_helper('FilebaseHelper');?>
 *
 * @param string $path_name
 * @param string $cache_directory
 * @return sfFilebasePlugin $filebase
 */
function get_filebase($path_name = null, $cache_directory = null)
{
    return sfFilebasePlugin::getInstance($path_name, $cache_directory);
}
 /**
  * Checks if this file is a child of the given filebase
  * directory.
  *
  * @see sfFilebasePlugin::fileLiesWithin
  * @param mixed sfFilebaseDirectory | string $file
  * @return boolean
  */
 public function liesWithin($file)
 {
     return $this->filebase->fileLiesWithin($this, $file);
 }
 public function getFile(sfFilebasePlugin $filebase = null)
 {
     $filebase === null && ($filebase = sfFilebasePlugin::getInstance());
     return $filebase[$this->getHash()];
 }
예제 #12
0
<?php

/*
 * This file is part of the symfony package.
 * (c) 2004-2006 Fabien Potencier <*****@*****.**>
 * 
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if ($_SERVER['argc'] < 2) {
    die("Usage: \$ php FilebaseTest.php application [environment]\r\nPlease call the test using a valid symfony app and environment. This is due to the fact that we test a doctrine behaviour which relies on a dataabase connection.\r\nExaple usage: \$ php FilebaseTest.php frontend test");
}
$_test_dir = realpath(dirname(__FILE__) . '/..');
require_once dirname(__FILE__) . '/../../../../config/ProjectConfiguration.class.php';
$configuration = new ProjectConfiguration(realpath($_test_dir . '/../../../'));
include $configuration->getSymfonyLibDir() . '/vendor/lime/lime.php';
// INITIALIZING DATABASE
$app_conf = ProjectConfiguration::getApplicationConfiguration($_SERVER['argv'][1], $_SERVER['argv'][2], true);
sfContext::createInstance($app_conf)->loadFactories();
###  INSTANCIATING FILEBASE
sfFilebasePlugin::createFilebase('test', realpath(dirname(__FILE__) . '/../assets'));
예제 #13
0
<?php

/**
 * This file is part of the sfFilebasePlugin package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package   de.optimusprime.sfFilebasePlugin
 * @author    Johannes Heinen <*****@*****.**>
 * @license   MIT license
 * @copyright 2007-2009 Johannes Heinen <*****@*****.**>
 */
foreach (sfConfig::get('app_sf_filebase_plugin_filebases', array('uploads' => array('path_name' => sfConfig::get('sf_upload_dir')))) as $id => $params) {
    $pathname = isset($params['path_name']) ? $params['path_name'] : null;
    $cache_directory = isset($params['cache_directory']) ? $params['cache_directory'] : null;
    $create = isset($params['create']) ? $params['create'] : false;
    sfFilebasePlugin::createFilebase($id, $pathname, $cache_directory, $create);
}
sfConfig::set('sf_default_filebase', sfFilebasePlugin::getDefault());
    protected function execute($arguments = array(), $options = array())
    {
        $root_directory_path = sfConfig::get('app_sf_filebase_plugin_path_name');
        $source_path = $arguments['source_path'];
        $file_mode = $options['file_mode'];
        if ($root_directory_path) {
            fwrite(STDOUT, "\n    Will use output directory specified in app.yml: {$root_directory_path}\n");
        } else {
            $root_directory_path = sfConfig::get('sf_upload_dir');
            if ($root_directory_path) {
                fwrite(STDOUT, "\n    No output directory specified in app.yml, will use {$root_directory_path}\n");
            } else {
                $error_message = <<<EOF
You have to specify a directory to store your uploaded files in. In apps/{your_app}/config/app.yml, write:
all:
  sf_filebase_plugin:
    path_name: /home/joshi/www/test/web/uploads/assets
EOF;
                throw new Exception($error_message);
            }
        }
        $filebase = sfFilebasePlugin::getInstance();
        if (!$filebase->fileExists() || !$filebase->isWritable()) {
            throw new Exception(sprintf('Filebase root directory %s does not exist or is write protected. Ensure that the directory exists in file system and that it is writable by the running php processes/apache users.', $filebase->getPathname()));
        }
        // initialize the database connection
        sfContext::createInstance($this->configuration);
        $databaseManager = sfContext::getInstance()->getDatabaseManager();
        $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
        $root = Doctrine::getTable('sfFilebaseDirectory')->getRootNode($options['env'], $arguments['application']);
        if ($root->isNew()) {
            throw new Exception('Filebase database was not initialized yet, execute sfFilebase:create-root task for doing this.');
        } else {
            $source = $filebase->getFilebaseFile($source_path);
            if (!$source->fileExists() || !$source->isReadable() || !$source instanceof sfFilebasePluginDirectory) {
                throw new Exception(sprintf("Source directory % s does not exist, is not readable or is even not a directory.", $source->getPathname()));
            }
            fwrite(STDOUT, "\n    Start synchronizing directory {$source_path}\n");
            function recurse(sfFilebasePluginFile $source, sfFilebaseDirectory $parent_dir, $file_mode)
            {
                try {
                    foreach ($source as $file) {
                        if ($file instanceof sfFilebasePluginDirectory) {
                            fwrite(STDOUT, sprintf("\n    Creating directory %s in %s\n", $source->getFilename(), $parent_dir->getFilename()));
                            $node = new sfFilebaseDirectory();
                            $hash = md5(uniqid(rand(), true));
                            $node->setHash($hash);
                            $node->setFilename($file->getFilename());
                            $node->save();
                            $node->getNode()->insertAsLastChildOf($parent_dir);
                            recurse($file, $node, $file_mode);
                        } else {
                            fwrite(STDOUT, sprintf("\n    Copying %s to %s\n", $source->getPathname(), $parent_dir->getFilename()));
                            $copy = $file->copy($source->getFilebase()->getPathname(), true);
                            $hash = $hash = md5(uniqid(rand(), true)) . '.' . $copy->getExtension();
                            $node = new sfFilebaseFile();
                            $node->setFilename($copy->getFilename());
                            $node->setHash($hash);
                            $node->save();
                            $node->getNode()->insertAsLastChildOf($parent_dir);
                            $move = $copy->move($hash);
                            $move->chmod($file_mode);
                        }
                    }
                } catch (Exception $e) {
                    throw new Exception((string) $e);
                }
            }
            recurse($source, $root, $file_mode);
        }
        fwrite(STDOUT, "\n    Import completed.\n");
        fwrite(STDOUT, "\n");
    }
예제 #15
0
<?php

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
include dirname(__FILE__) . '/../bootstrap/unit.php';
$t = new lime_test(81, new lime_output_color());
$t->diag('Ok, let\'s take a look... These tests are as incomplete as tests can be.');
$t->diag('Any exeptions thrown during testrun may cause in file-permission issues. After a test-run failed, please manually clean up the standard-filebase-directory unter sfConfig::get(sf_upload_dir) and run php ./symfony fix-perms task as a system administrator.');
###  INSTANCIATING FILEBASE
$t->isa_ok(new sfFilebasePlugin(), 'sfFilebasePlugin', 'sfFilebasePlugin instanziated.');
$t->diag('Performing some file operations.');
$f = new sfFilebasePlugin();
$t->diag('Lets try to generate a directory with mkDir().');
$dir = null;
try {
    $t->isa_ok($dir = $f->mkDir('my_dir', 0777), 'sfFilebasePluginDirectory', 'mkDir() successfully created a new directory.');
} catch (Exception $e) {
    $t->fail((string) $e->getMessage());
    $t->diag('Maybe the directory already exists....');
}
$t->ok($dir instanceof sfFilebasePluginDirectory, 'mkDir() returns instance of sfFilebasePluginDirectory.');
$t->diag('Directory was created, now try to delete it.');
$t->is($dir->fileExists(), true, 'File check with fileExists() is true.');
$t->is($dir->isWritable(), true, 'File check with is Writable() is true');
try {
    $success = $dir->delete();
} catch (Exception $e) {
    $t->diag((string) $e->getMessage());
    $t->diag('Maybe the directory does not exist or is write protected.');
예제 #16
0
 /**
  * Sets the pathname for one tuple
  *
  * @param sfFilebasePluginFile | string $file
  * @return Doctrine_Template_File
  */
 public function setFile($file)
 {
     $file = $this->filebase->getFilebaseFile($file);
     $this->_invoker[$this->getOption('name')] = $file->getRelativePathFromFilebaseDirectory();
     return $this;
 }
예제 #17
0
            echo link_to('<span>' . __('Edit') . '</span>', 'sf_filebase_directory_edit', array('id' => $node->getId()), array('class' => 'directory-edit-link'));
            ?>
                <?php 
            echo link_to('<span>' . __('Delete') . '</span>', '@sf_filebase_directory_delete?id=' . $node->getId(), array('class' => 'directory-delete-link', 'method' => 'delete', 'confirm' => __('Do you really want to delete the whole directory and its contents?')));
            ?>
              </span>
            </div>
          </li>
        <?php 
        } else {
            ?>
          <?php 
            if (!$tag || $node->hasTag($tag)) {
                ?>
            <?php 
                $file = sfFilebasePlugin::getInstance()->getFilebaseFile($node->getHash());
                ?>
            <li class="file<?php 
                $file instanceof sfFilebaseImage && (print ' file-image');
                ?>
">
              <div class="contents">
                <?php 
                #if($file->isImage()):
                ?>
                  <?php 
                #$url = url_for('@sf_filebase_display_image?width=580&file='.$node->getId())
                ?>
                <?php 
                #else:
                ?>
function url_for_asset($path_name)
{
    $f = sfFilebasePlugin::getInstance();
}
 /**
  * Returns uploaded files as an array consisting of instances of
  * sfFilebasePluginUploadedFile.
  *
  * This can be useful when you are using sfFilebasePluginValidatorFile
  * and want to bind the instances to a sfForm:
  *
  * * $my_form->bind(
  * *   $request->getParameter('foo'),
  * *   $request->getUploadedFiles('foo')
  * * );
  *
  * @param  string $name: The prefix if set, e.g.
  *         <input type="file" name="hanswurst[file]/>
  *         access by $request->getUploadedFilese('hanswurst')
  * @return array sfFilebasePluginUploadedFile $files
  */
 public function getUploadedFiles($name = null)
 {
     return sfFilebasePlugin::getInstance()->getUploadedFiles($name);
 }
<?php

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
include dirname(__FILE__) . '/../bootstrap/unit.php';
try {
    $t = new lime_test(87, new lime_output_color());
    $t->diag('Ok, let\'s take a look... These tests are as incomplete as tests can be.');
    $t->diag('Any exeptions thrown during testrun may cause in file-permission issues. After a test-run failed, please manually clean up the standard-filebase-directory unter sfConfig::get(sf_upload_dir) and run php ./symfony fix-perms task as a system administrator.');
    $t->isa_ok($f = sfFilebasePlugin::getInstance('test'), 'sfFilebasePlugin', 'sfFilebasePlugin instanziated.');
    $t->ok($f->getCacheDirectory()->fileExists(), 'sfFilebasePlugin::getCacheDirectory()::fileExists() is true');
    ### CHECK ON FILES
    $t->diag('Test some file properties on a non existing file.');
    $t->isa_ok($f3 = $f['notexist'], 'sfFilebasePluginFile', 'Fetched a (non existing) instanceof of sfFilebasePluginFile via sfFilebasePlugin::offsetGet() (array access).');
    $t->ok(!$f3->fileExists(), 'sfFilebasePluginFile::fileExists returns false');
    $t->ok(!$f3->isWritable(), 'Non existing files are not writable');
    $t->ok(!$f3->isReadable(), 'Non existing files are not readable');
    ### CREATE A NEW FILE
    $t->diag('Test some file properties on a existing file...');
    $t->isa_ok($f4 = $f->touch('analyzeme', 0777), 'sfFilebasePluginFile', 'File created by sfFilebasePlugin::touch() with permissions 0777');
    $t->ok($f4->fileExists(), 'The new file exists in sf');
    $t->ok($f4->isReadable(), 'The new file is readable');
    $t->ok($f4->isWritable(), 'The new file is writable');
    $t->diag('Test if a file lies within the filebase');
    $t->ok(!$f->getFilebaseFile('/test')->getIsInFilebase(), '/test does not lie within the filebase directory');
    $t->ok($f4->getIsInFilebase(), 'This file lies within its filebase directory');
    $t->diag('Locate some files by its hash');
    $t->ok($hash = $f4->getHash(), sprintf('sfFilebasePluginFile::getHash() returns %s', $hash));
    $t->isa_ok($f->getFileByHash($hash), 'sfFilebasePluginFile', sprintf('sfFilebasePlugin::getFileByHash(%s) returns the file.', $hash));
 /**
  * Moves an uploaded File to specified Destination.
  * Inclusion and exclusion rules consist of regex-strings,
  * they are used to check the target filenames against them.
  * Exclusion:   Matched filenames throw exceptions.
  * Inclusion:  Matched filenames will be passed as valid filenames.
  *
  * You should wrap this method into a try-catch block because many
  * things can go wrong during or after the upload, so if you upload
  * many files and did not validate them before, this would be a good
  * starting point do to some "low level" validation.
  *
  * $destination can be a string (absolute or relative pathname) or an
  * instance of sfFilebasePluginFile, it is the directory, not the full pathName of
  * the new file. The file can be renamed by setting $file_name, otherwise
  * the original name will be taken as filename.
  *
  * @param mixed $tmp_file
  * @param mixed $destination_directory: The directory the file will be moved in.
  * @param boolean $allow_overwrite True if existing files should be overwritten
  * @param array $inclusion_rules
  * @param array $exclusion_rules
  * @param string $file_name: If given, file will be renamed when moving.
  * @throws sfFilebasePluginException
  * @return sfFilebasePluginFile $moved_file
  */
 public function moveUploadedFile(sfFilebasePluginUploadedFile $tmp_file, $destination_directory, $allow_overwrite = true, $chmod = 0777, array $inclusion_rules = array(), $exclusion_rules = array(), $file_name = null)
 {
     $destination_directory = $this->filebase->getFilebaseFile($destination_directory);
     // Error handling
     if ($tmp_file->isError()) {
         switch ($tmp_file->getError()) {
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_EXTENSION:
                 throw new sfFilebasePluginException('Upload error thrown by extension.', sfFilebasePluginUploadedFile::UPLOAD_ERR_EXTENSION);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_PARTIAL:
                 throw new sfFilebasePluginException('Upload error: Upload interrupted.', sfFilebasePluginUploadedFile::UPLOAD_ERR_PARTIAL);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_CANT_WRITE:
                 throw new sfFilebasePluginException('Upload error: Cannot write temporary file.', sfFilebasePluginUploadedFile::UPLOAD_ERR_CANT_WRITE);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_EXTENSION:
                 throw new sfFilebasePluginException('Upload error: Extension error.', sfFilebasePluginUploadedFile::UPLOAD_ERR_EXTENSION);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_FORM_SIZE:
                 throw new sfFilebasePluginException('Upload error: Form size exceeded.', sfFilebasePluginUploadedFile::UPLOAD_ERR_FORM_SIZE);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_INI_SIZE:
                 throw new sfFilebasePluginException('Upload error: Ini size exceeded.', sfFilebasePluginUploadedFile::UPLOAD_ERR_INI_SIZE);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_NO_FILE:
                 throw new sfFilebasePluginException('Upload error: no file was uploaded.', sfFilebasePluginUploadedFile::UPLOAD_ERR_NO_FILE);
             case sfFilebasePluginUploadedFile::UPLOAD_ERR_NO_TMP_DIR:
                 throw new sfFilebasePluginException('Upload error: There is no temp dir.', sfFilebasePluginUploadedFile::UPLOAD_ERR_NO_TMP_DIR);
                 return false;
         }
     }
     // Validation, excuting inclusion rules
     foreach ($inclusion_rules as $rule) {
         if (!preg_match($rule, $tmp_file->getOriginalName())) {
             throw new sfFilebasePluginException(sprintf('Inclusion-Validation failed while uploading file %s: Rule %s', $tmp_file->getOriginalName(), $rule));
         }
     }
     // Valdating using exclusion rules
     foreach ($exclusion_rules as $rule) {
         if (preg_match($rule, $tmp_file->getOriginalName())) {
             throw new sfFilebasePluginException(sprintf('Exclusion-Validation failed while uploading file %s: Rule %s', $tmp_file->getOriginalName(), $rule));
         }
     }
     if (!$destination_directory instanceof sfFilebasePluginDirectory) {
         throw new sfFilebasePluginException(sprintf('Destination %s is not a directory.', $destination_directory->getPathname()));
     }
     $destination = null;
     // Filename given? Rename file...
     if ($file_name === null) {
         $destination = $this->filebase->getFilebaseFile($destination_directory->getPathname() . '/' . $tmp_file->getOriginalName());
     } else {
         $file_name = (string) $file_name;
         if (strlen($file_name > 0)) {
             $destination = $this->filebase->getFilebaseFile($destination_directory->getPathname() . '/' . $file_name);
         }
     }
     if (!$this->filebase->isInFilebase($destination)) {
         throw new sfFilebasePluginException(sprintf('Destination %s does not lie within Filebase %s, access denied due to security reasons.', $destination->getPathname(), $this->filebase->getPathname()));
     }
     if ($destination->fileExists()) {
         if ($allow_overwrite) {
             if (!$destination->isWritable()) {
                 throw new sfFilebasePluginException(sprintf('File %s is write protected.', $destination->getPathname()));
             }
         } else {
             throw new sfFilebasePluginException(sprintf('Destination file %s already exists', $destination->getPathname()));
         }
     } else {
         if (!$destination_directory->isWritable()) {
             throw new sfFilebasePluginException(sprintf('Destination directory %s is write protected', $destination_directory->getPathname()));
         }
     }
     if (!@move_uploaded_file($tmp_file->getTempName(), $destination->getPathname())) {
         throw new sfFilebasePluginException(sprintf('Error while moving uploaded file %s', $tmp_file->getOriginalName()));
     }
     $destination->chmod($chmod);
     return $destination;
 }
 /**
  * Returns filename for a cached thumbnail, calculated
  * by its properties and dimensions.
  *
  * @param sfFilebasePluginFile $file
  * @param array $thumbnail_properties
  * @return sfFilebasePluginImage $filename
  */
 public function getThumbnailFileinfo(sfFilebasePluginImage $file, $dimensions, $mime)
 {
     $thumbnail_properties = $this->getScaledImageData($file, $dimensions);
     // Wrap in sfFilebasePluginImage because isImage may return false if file does not exist.
     return new sfFilebasePluginThumbnail($this->filebase->getFilebaseFile($this->filebase->getCacheDirectory() . DIRECTORY_SEPARATOR . $this->filebase->getHashForFile($file) . '_' . $thumbnail_properties['new_width'] . '_' . $thumbnail_properties['new_height'] . '.' . (sfFilebasePluginUtil::getExtensionByMime($mime) === null ? $thumbnail_properties['extension'] : sfFilebasePluginUtil::getExtensionByMime($mime))), $this->filebase, $file);
 }
 /**
  * Saves the uploaded file.
  *
  * This method can throw exceptions if there is a problem when saving the file.
  *
  * If you don't pass a file name, it will be generated by the generateFilename method.
  * This will only work if you have passed a path when initializing this instance.
  *
  * @param  string $file      The file path to save the file
  * @param  int    $fileMode  The octal mode to use for the new file
  * @param  bool   $create    Indicates that we should make the directory before moving the file
  * @param  int    $dirMode   The octal mode to use when creating the directory
  *
  * @return string The filename without the $this->path prefix
  *
  * @throws Exception
  */
 public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777)
 {
     $filebase = null;
     if ($file === null) {
         if ($this->originalName === null) {
             $file = $this->generateFilename();
         } else {
             $file = $this->originalName;
         }
     }
     // Check if $file contains an absolute pathname
     if (sfFilebasePluginUtil::isAbsolutePathname($file)) {
         $fb = sfFilebasePlugin::getInstance();
         $f = $fb->getFilebaseFile($file);
         $filebase = sfFilebasePlugin::getInstance($f->getPath(), null, $create);
     } else {
         if ($this->path === null) {
             $filebase = sfFilebasePlugin::getInstance(null, null, $create);
         } else {
             $filebase = sfFilebasePlugin::getInstance($this->path, null, $create);
         }
     }
     $file = $filebase->getFilebaseFile($file);
     // copy the temp file to the destination file
     $f = $filebase->copyFile($this->getTempName(), $file->getPathname());
     // chmod our file
     $file->chmod($fileMode);
     $this->savedName = $file->getPathname();
     return $file;
 }