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'] = new sfFilebasePluginValidatorFile(array('path' => sfFilebasePlugin::getInstance()->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 filebase by options */ public function setUp() { if (!($filebase_id = $this->getOption('filebase', null))) { throw new sfFilebasePluginException('You must specify a filebase to use this behaviour'); } $this->filebase = sfFilebasePlugin::getInstance($filebase_id); if (!$this->filebase->fileExists()) { throw new sfFilebasePluginException('The filebase directory does not exist.'); } }
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; } }
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; }
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; }
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()); } }
<?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));
/** * 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); }
public function getFile(sfFilebasePlugin $filebase = null) { $filebase === null && ($filebase = sfFilebasePlugin::getInstance()); return $filebase[$this->getHash()]; }
/** * 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); }
function url_for_asset($path_name) { $f = sfFilebasePlugin::getInstance(); }
/** * 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; }
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: ?>
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"); }