public function configure() { $this->widgetSchema['file'] = new sfWidgetFormInputFile(); $fileValidator = new sfValidatorFile(); $fileValidator->setOption('mime_type_guessers', array()); $this->validatorSchema['file'] = $fileValidator; }
protected function doClean($value) { set_time_limit(0); $uploads = new Doctrine_Collection($this->getOption('model')); $fileValidator = new sfValidatorFile(array('mime_types' => 'web_images')); $descriptionValidator = new sfValidatorString(array('max_length' => 255, 'required' => false, 'trim' => true)); foreach ($value as $file) { $validatedDescription = $descriptionValidator->clean($file['description']); if (isset($file['file']) && is_array($file['file']) && $file['file']['tmp_name']) { $validatedFile = $fileValidator->clean($file['file']); try { $uploadedFileRecord = tsUpload::create($validatedFile, $this->getOption('rule'))->process(); } catch (tsUploadException $e) { throw new sfValidatorError($this, $e->getMessage()); } $uploadedFileRecord->name = $validatedFile->getOriginalName(); $uploadedFileRecord->description = $validatedDescription; $uploads[] = $uploadedFileRecord; } elseif (isset($file['id'])) { $uploadedFileRecord = Doctrine::getTable($this->getOption('model'))->findOneById($file['id']); if ($uploadedFileRecord) { $uploadedFileRecord->description = $validatedDescription; $uploads[] = $uploadedFileRecord; } } if ($this->getOption('max_count') && count($uploads) > $this->getOption('max_count')) { throw new sfValidatorError($this, 'max_count', array('value' => $value, 'max_count' => $this->getOption('max_count'))); } } return $uploads; }
public function configure() { $this->widgetSchema['file'] = new sfWidgetFormInputFile(); $fileValidator = new sfValidatorFile(array('path' => sfConfig::get('sf_cache_dir'))); $fileValidator->setOption('mime_type_guessers', array()); $this->validatorSchema['file'] = $fileValidator; }
public function validatePhoto($validator, $value, $arguments) { $_validator = new sfValidatorFile(); try { $value['file'] = $_validator->clean($value['file']); } catch (sfValidatorError $e) { if ('required' !== $e->getCode()) { throw $e; } $value['description'] = ''; $value['file'] = null; } return $value; }
public function configure($options = array(), $messages = array()) { $this->addRequiredOption('gaufrette'); parent::configure($options, $messages); $this->setOption('validated_file_class', 'sfGaufretteValidatedFile'); $this->setOption('path', $options['gaufrette']); }
protected function doClean($value) { // Getting uploaded file (still in tmp at this stage) $validatedFile = parent::doClean($value); // Loading BitTorrent class require "../lib/bittorrent/Autoload.php"; // Open a new torrent instance $torrent = new PHP_BitTorrent_Torrent(); // Loading it $torrent->loadFromTorrentFile($validatedFile->getTempName()); // Generating hash $hash = sha1(PHP_BitTorrent_Encoder::encode($torrent->getInfo())); // I want to use this hash outside this class, not clean at all, shame on me ^^ define('HASH', $hash); define('SIZE', $torrent->getSize()); // Looking if hash is already posted $sh = Doctrine_Query::create()->select('COUNT(*)')->from("Uploads")->where("hash = ?", $hash)->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR); if ($sh > 0) { throw new sfValidatorError($this, 'already', array('hash' => $hash)); } // Private mode $i = $torrent->getInfo(); if ($this->getOption('private') != $i['private']) { throw new sfValidatorError($this, 'private', array('private' => $this->getOption('private'))); } // Checking if announce URL is correct /*if ($this->getOption('announce') != $torrent->getAnnounce()) throw new sfValidatorError($this, 'announce', array('announce' => $this->getOption('announce'))); */ return $validatedFile; }
/** * @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; }
/** * @see sfValidatorBase */ protected function doClean($value) { $clean = array(); foreach ($value as $file) { $clean[] = parent::doClean($file); } return $clean; }
protected function doClean($value) { try { return parent::doClean($value); } catch (sfValidatorError $e) { if ($e->getCode() == 'max_size') { $arguments = $e->getArguments(true); throw new sfValidatorError($this, 'max_size', array('max_size' => opConfig::get('image_max_filesize'), 'size' => $arguments['size'])); } throw $e; } }
protected function doClean($value) { $file = parent::doClean($value); if ($file instanceof sfValidatedFile) { try { $client = new Google_Client(); $client->setAuthConfigFile($file->getTempName()); } catch (Google_Exception $e) { throw new sfValidatorError($this, (string) $e); } } return $file; }
public function executeUpload(sfWebRequest $request) { $result = 'All broken :('; try { //@todo: added CSRF check; $files = $request->getFiles(); $fileData = array_pop($files); $validator = new sfValidatorFile(array('max_size' => 1024 * 1024, 'mime_types' => array('image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif', 'application/octet-stream'))); $file = $validator->clean($fileData); $file instanceof sfValidatedFile; $uploader = new ImageUploader(); $uploaded = $uploader->login()->upload($file->getTempName()); $photo = new Photo(); $photo->name = $uploaded->image; $photo->thumb = $uploaded->thumb; $photo->save(); $result = array('id' => $photo->getId(), 'image' => $uploaded->image, 'thumb' => $uploaded->thumb); } catch (Exception $e) { $result = $e->getMessage(); } return $this->renderText(json_encode($result)); }
protected function doClean($value) { $value = parent::doClean($value); if ($this->hasOption('allowed_extensions')) { $extensions = $this->getOption('allowed_extensions'); if (!is_array($extensions)) { $extensions = array($extensions); } if (!in_array(ltrim($value->getOriginalExtension(), '.'), $extensions)) { throw new sfValidatorError($this, 'invalid_extension'); } } return $value; }
protected function doClean($value) { //ftheeten 2016 02 22 $disableXSDValidation = sfConfig::get('dw_disableXSDValidation'); parent::doClean($value); libxml_use_internal_errors(true); $xml = new DOMDocument(); $errorSchema = new sfValidatorErrorSchema($this); $errorSchemaLocal = new sfValidatorErrorSchema($this); if (!file_exists($value['tmp_name'])) { throw new sfValidatorError($this, 'unreadable_file'); } if (!$xml->load($value['tmp_name'])) { throw new sfValidatorError($this, 'unreadable_file'); } //ftheeten 2016 02 22 to disable the validation of XML (aim is avoiding resolving external schemas) if ($disableXSDValidation === false) { if (!$xml->schemaValidate(sfConfig::get('sf_web_dir') . $this->getOption('xml_path_file'))) { $errorSchemaLocal->addError(new sfValidatorError($this, 'invalid_format'), 'invalid_format_ABCD'); $errors = libxml_get_errors(); $i = 0; foreach ($errors as $error) { $error_msg = $this->displayXmlError($error); $errorSchemaLocal->addError(new sfValidatorError($this, $error_msg), 'invalid_line'); if ($i++ > 100) { break; } } libxml_clear_errors(); if (count($errorSchemaLocal)) { $errorSchema->addError($errorSchemaLocal); } if (count($errorSchema)) { throw new sfValidatorErrorSchema($this, $errorSchema); } } } $class = $this->getOption('validated_file_class'); return new $class($value['name'], 'text/xml', $value['tmp_name'], $value['size'], $this->getOption('path')); }
/** * Check dimensions, perform resize and then call parent validator. * * @param array $value * @return sfValidatedFile */ protected function doClean($value) { $file = parent::doClean($value); // resize the image by default if ($this->getOption('resize')) { // first of all, resize to given maximum and/or width but check for exception // if unsupported file format // FIXME this isn't elegant and should fail better (mime_types check should fail first before resize attempted) try { $image = new ImageTransform($file->getTempName(), $file->getType()); $image->fit($this->getOption('max_width'), $this->getOption('max_height')); $image->save($file->getTempName()); } catch (Exception $e) { // do nothing } } else { // fetch image info list($width, $height, $type, $attr) = getimagesize($file->getTempName()); // do we have some exact required dimensions? if ($this->getOption('required_width') !== false || $this->getOption('required_height') !== false) { $passes_width = ($required_width = $this->getOption('required_width')) ? $width == $required_width : true; $passes_height = ($required_height = $this->getOption('required_height')) ? $height == $required_height : true; if (!$passes_height || !$passes_width) { throw new sfValidatorError($this, 'required_dimensions', array('width' => $width, 'height' => $height, 'required_width' => $required_width, 'required_height' => $required_height)); } } // check both dimensions to show useful error about both width and height if needed if ($width > $this->getOption('max_width') && $height > $this->getOption('max_height')) { throw new sfValidatorError($this, 'max_dimensions', array('width' => $width, 'height' => $height, 'max_width' => $this->getOption('max_width'), 'max_height' => $this->getOption('max_height'))); } elseif ($width > $this->getOption('max_width')) { throw new sfValidatorError($this, 'max_width', array('width' => $width, 'max_width' => $this->getOption('max_width'))); } elseif ($height > $this->getOption('max_height')) { throw new sfValidatorError($this, 'max_height', array('height' => $height, 'max_height' => $this->getOption('max_height'))); } } // now tell sfValidatorFile to do its own checks return $file; }
/** * 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()); } }
protected function configure($options = array(), $messages = array()) { parent::configure($options, $messages); $this->setOption('mime_categories', 'web_images'); $this->setOption('path', sfConfig::get('sf_web_dir') . '/images/store'); }
/** * The input value must be an array potentially containing two * keys, newfile and persistid. newfile must contain an array of * the following subkeys, if it is present: * * * tmp_name: The absolute temporary path to the newly uploaded file * * name: The original file name (optional) * * type: The file content type (optional) * * error: The error code (optional) * * size: The file size in bytes (optional) * * The persistid key allows lookup of a previously uploaded file * when no new file has been submitted. * * A RARE BUT USEFUL CASE: if you need to prefill this cache before * invoking the form for the first time, you can instantiate this * validator yourself: * * $vfp = new aValidatorFilePersistent(); * $guid = aGuid::generate(); * $vfp->clean( * array( * 'newfile' => * array('tmp_name' => $myexistingfile), * 'persistid' => $guid)); * * Then set array('persistid' => $guid) as the default value * for the file widget. This logic is most easily encapsulated in * the configure() method of your form class. * * @see sfValidatorFile * @see sfValidatorBase */ public function clean($value) { $user = sfContext::getInstance()->getUser(); $persistid = false; if (isset($value['persistid'])) { $persistid = $value['persistid']; } $newFile = false; $persistentDir = $this->getPersistentDir(); if (!self::validPersistId($persistid)) { $persistid = false; } $cvalue = false; // Why do we tolerate the newfile fork being entirely absent? // Because with persistent file upload widgets, it's safe to // redirect a form submission to another action via the GET method // after validation... which is extremely useful if you want to // split something into an iframed initial upload action and // a non-iframed annotation action and you need to be able to // stuff the state of the form into a URL and do window.parent.location =. // As long as we tolerate the absence of the newfile button, we can // rebuild the submission from what's in // getRequest()->getParameterHolder()->getAll(), and that is useful. if (!isset($value['newfile']) || $this->isEmpty($value['newfile'])) { if ($persistid !== false) { $filePath = "{$persistentDir}/{$persistid}.file"; $data = false; if (file_exists($filePath)) { $dataPath = "{$persistentDir}/{$persistid}.data"; // Don't let them expire touch($filePath); touch($dataPath); $data = file_get_contents($dataPath); if (strlen($data)) { $data = unserialize($data); } } if ($data) { $cvalue = $data; } } } else { $newFile = true; $cvalue = $value['newfile']; } // This will throw an exception if there is a validation error. // That's a good thing: we don't want to save it for reuse // in that situation. try { $result = parent::clean($cvalue); } catch (Exception $e) { // If there is a validation error stop keeping this // file around and don't display the reassuring // "you don't have to upload again" message side by side // with the validation error. if ($persistid !== false) { $infoPath = "{$persistentDir}/{$persistid}.data"; $filePath = "{$persistentDir}/{$persistid}.file"; @unlink($infoPath); @unlink($filePath); } throw $e; } if ($newFile) { // Expiration of abandoned stuff has to happen somewhere self::removeOldFiles($persistentDir); if ($persistid !== false) { $filePath = "{$persistentDir}/{$persistid}.file"; copy($cvalue['tmp_name'], $filePath); $data = $cvalue; $data['newfile'] = true; $data['tmp_name'] = $filePath; self::putFileInfo($persistid, $data); } } elseif ($persistid !== false) { $data = self::getFileInfo($persistid); if ($data !== false) { $data['newfile'] = false; self::putFileInfo($persistid, $data); } } return $result; }
/** * @param sfWebRequest $request * @return string */ public function executeModalUpload(sfWebRequest $request) { $this->forward404Unless($request->isXmlHttpRequest()); $result = array(); $decision_id = $this->getUser()->getAttribute('decision_id', null, 'sfGuardSecurityUser'); if (!empty($decision_id)) { $decision = DecisionTable::getInstance()->getDecisionForUser($this->getUser()->getGuardUser(), $decision_id); $this->forward404Unless(is_object($decision)); } else { $this->forward404(); } $fileValidator = new sfValidatorFile(array('required' => true)); $decisionImporter = new DecisionImporter(); $decisionImporter->setDecision($decision); $decisionImporter->setCreatedAndUpdatedBy(Alternative::generateUpdateAndCreatedBy($this->getUser()->getGuardUser())); foreach ($request->getFiles('files') as $file) { $validatedFile = $fileValidator->clean($file); $decisionImporter->setFile($validatedFile); $result = $decisionImporter->import(); } $dashboard_role = $decision->getDashboardRole(); if ($dashboard_role) { foreach ($decisionImporter->getAlternatives() as $alternative) { foreach ($decision->getCriterion() as $criterion) { $planned_alternative_measurement = new PlannedAlternativeMeasurement(); $planned_alternative_measurement->setAlternative($alternative); $planned_alternative_measurement->setCriterion($criterion); $dashboard_role->PlannedAlternativeMeasurement->add($planned_alternative_measurement); } } $dashboard_role->PlannedAlternativeMeasurement->save(); } $this->setLayout(false); $this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8'); return $this->renderText(json_encode(array('status' => 'success', 'items' => $result))); }
public function executeAlternativeImport(sfWebRequest $request) { $this->forward404Unless($request->isXmlHttpRequest()); $decision_id = $request->getParameter('decision_id', false); /** @var Decision $decision */ $decision = DecisionTable::getInstance()->getDecisionForUser($this->getUser()->getGuardUser(), $decision_id); $fileValidator = new sfValidatorFile(array('required' => true)); $importer = new AlternativeImporter(); $importer->setDecision($decision); $importer->setCreatedAndUpdatedBy(Alternative::generateUpdateAndCreatedBy($this->getUser()->getGuardUser())); foreach ($request->getFiles('files') as $file) { $validatedFile = $fileValidator->clean($file); $importer->setFile($validatedFile); $importer->import(); } $dashboard_role = $decision->getDashboardRole(); if ($dashboard_role) { foreach ($importer->getAlternatives() as $alternative) { foreach ($decision->getCriterion() as $criterion) { $planned_alternative_measurement = new PlannedAlternativeMeasurement(); $planned_alternative_measurement->setAlternative($alternative); $planned_alternative_measurement->setCriterion($criterion); $dashboard_role->PlannedAlternativeMeasurement->add($planned_alternative_measurement); } } $dashboard_role->PlannedAlternativeMeasurement->save(); } $this->setLayout(false); $this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8'); return $this->renderText(json_encode(array(array()))); }
/** * @param sfWebRequest $request * @return sfView * @throws Doctrine_Collection_Exception * @throws sfError404Exception */ public function executeImportFromExcel(sfWebRequest $request) { $decision_id = $request->getParameter('decision_id', false); $decision = DecisionTable::getInstance()->getDecisionForUser($this->getUser()->getGuardUser(), $decision_id); $this->forward404Unless(is_object($decision)); $fileValidator = new sfValidatorFile(array('required' => true, 'mime_types' => array('application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/msexcel', 'application/x-msexcel', 'application/x-ms-excel', 'application/x-excel', 'application/x-dos_ms_excel', 'application/xls', 'application/x-xls', 'application/vnd.ms-office', 'application/zip'))); try { $validatedFile = $fileValidator->clean($request->getFiles('file')); } catch (Exception $e) { return $this->renderText(json_encode(array('status' => 'error', 'message' => $e->getMessage()))); } $importer = new AlternativeImporter(); $importer->setDecision($decision); $importer->setFile($validatedFile); return $this->renderText(json_encode(array('status' => 'success', 'html' => $this->getComponent('alternative', 'importCustomFields', array('data' => $importer->prepareData(), 'decision_id' => $decision_id))))); }
/** * DOCUMENT ME * @param mixed $file * @param mixed $fallback * @return mixed */ protected function getMimeType($file, $fallback) { // The microsoft guesser needs access to the original filename. // For reasons I'm not sure of, it doesn't work as a dynamic method // with call_user_func. $match = $this->guessMicrosoft($file); if (!is_null($match)) { return $match; } return parent::getMimeType($file, $fallback); }
public function executeUpload(sfWebRequest $request) { $this->forward404Unless($request->isXmlHttpRequest()); /** @var Role $role */ $role = $this->getRoute()->getObject(); $response = array(); // Load files if ($request->getMethod() == 'GET') { foreach ($role->Files as $uploadedFile) { $response[] = $uploadedFile->getResponseObject(); } } else { $dir_path = '/role'; $fileValidator = new sfValidatorFile(array('required' => true, 'path' => sfConfig::get('sf_upload_dir') . $dir_path)); foreach ($request->getFiles('files') as $file) { $validatedFile = $fileValidator->clean($file); $uploadedFile = new UploadedFile(); $uploadedFile->path = $dir_path . '/' . $validatedFile->save(); $uploadedFile->mime_type = $validatedFile->getType(); $uploadedFile->name = $validatedFile->getOriginalName(); $uploadedFile->save(); $role->Files->add($uploadedFile); $response[] = $uploadedFile->getResponseObject(); } $role->save(); } $this->setLayout(false); $this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8'); return $this->renderText(json_encode($response)); }
public function getMimeTypesFromCategory($category) { return parent::getMimeTypesFromCategory($category); }
public function executeImport(sfWebRequest $request) { $this->forward404Unless($request->isXmlHttpRequest()); $decision_id = $request->getParameter('decision_id', false); /** @var Decision $decision */ $decision = DecisionTable::getInstance()->getDecisionForUser($this->getUser()->getGuardUser(), $decision_id); $fileValidator = new sfValidatorFile(array('required' => true)); $importerClass = $this->model . 'Importer'; $importer = new $importerClass(); $importer->setDecision($decision); if ($this->model == 'Alternative') { $importer->setCreatedAndUpdatedBy(Alternative::generateUpdateAndCreatedBy($this->getUser()->getGuardUser())); } foreach ($request->getFiles('files') as $file) { $validatedFile = $fileValidator->clean($file); $importer->setFile($validatedFile); $importer->import(); } $this->setLayout(false); $this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8'); return $this->renderText(json_encode(array(array()))); }