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 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 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)); }
/** * * 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 browser-submitted file name (optional, but necessary to distinguish amongst Microsoft Office formats) * type: The browser-submitted file content type (required although our guessers never trust it) * 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 * @param mixed $value * @return mixed */ public function clean($value) { $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']; } if (isset($cvalue['name'])) { $this->originalName = $cvalue['name']; } else { $this->originalName = ''; } 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; // It's useful to know the mime type and true extension for // supplying previews and icons $extensionsByMimeType = array_flip(aMediaTools::getOption('mime_types')); if (!isset($cvalue['type'])) { // It's not sensible to trust a browser-submitted mime type anyway, // so don't force non-web invocations of this code to supply one $cvalue['type'] = 'unknown/unknown'; } $data['mime_type'] = $this->getMimeType($filePath, $cvalue['type']); if (isset($extensionsByMimeType[$data['mime_type']])) { $data['extension'] = $extensionsByMimeType[$data['mime_type']]; } self::putFileInfo($persistid, $data); } } elseif ($persistid !== false) { $data = self::getFileInfo($persistid); if ($data !== false) { $data['newfile'] = false; self::putFileInfo($persistid, $data); } } return $result; }
/** * 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; }
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()))); }
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)); }
/** * @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))))); }
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 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))); }