/** * Checks if the passed value is valid. * * @param UploadedFile $file The value that should be validated * @param Constraint $constraint The constraint for the validation */ public function validate($file, Constraint $constraint) { if (!in_array($file->getMimeType(), $this->mimeTypes)) { $this->context->buildViolation($constraint->messageMimeTypes)->atPath('file')->addViolation(); } if ($file->getSize() > $file->getMaxFilesize()) { $this->context->buildViolation($constraint->messageMaxSize, array('%max_size%' => $file->getMaxFilesize()))->atPath('file')->addViolation(); } }
/** * @param int $size * @return int */ public function maxUploadSize($size = null) { if (func_num_args() === 0) { return $this->maxUploadSize; } return $this->maxUploadSize = min((int) $size, UploadedFile::getMaxFilesize()); }
/** * Upload an image. * @param \Symfony\Component\HttpFoundation\FileBag $p_file * @param string $p_rootDir * @param string $p_basePath * @param string $p_folder * @param string $p_path * @return \Symfony\Component\HttpFoundation\JsonResponse * @throws \Exception */ public function uploadImage(FileBag $p_file, $p_rootDir, $p_basePath, $p_folder, $p_path) { $arrExtension = array("gif", "jpeg", "jpg", "png"); $folder = $this->obtainFolder($p_rootDir, $p_folder); $path = $this->obtainPath($p_basePath, $p_path); $response = new JsonResponse(); // ------------------------- DECLARE ---------------------------// if ($p_file == null) { $response->setData(array("error" => "No file received.")); return $response; } $file = $p_file->get("file"); if ($file == null) { $response->setData(array("error" => "No file received.")); return $response; } if ($file->getSize() > UploadedFile::getMaxFilesize()) { $response->setData(array("error" => "File too big.")); return $response; } // Cheks image type. $extension = $file->guessExtension(); $mime = $file->getMimeType(); if (($mime == "image/gif" || $mime == "image/jpeg" || $mime == "image/pjpeg" || $mime == "image/x-png" || $mime == "image/png") && in_array($extension, $arrExtension)) { // Generates random name. $name = sha1(uniqid(mt_rand(), true)) . '.' . $file->guessExtension(); // Save file in the folder. $file->move($folder, $name); $response->setData(array("link" => $path . '/' . $name)); return $response; } $response->setData(array("error" => "File not supported.")); return $response; }
/** * Constructor */ public function __construct() { // Set default size equal to upload_max_filesize param in php.ini config $this->_uploadMaxSize = UploadedFile::getMaxFilesize(); // Set default file name $this->_fileName = 'uploaded_on_' . date('Y-m-d_H-i-s'); }
/** * Checks the current request to see if it is a postback containing a file upload * for this particular widget. */ protected function checkUploadPostback() { $fileName = null; try { $uploadedFile = Input::file('file_data'); if (!is_object($uploadedFile)) { return; } $fileName = $uploadedFile->getClientOriginalName(); // Don't rely on Symfony's mime guessing implementation, it's not accurate enough. // Use the simple extension validation. $allowedAssetTypes = Config::get('cms.allowedAssetTypes'); if (!$allowedAssetTypes) { $allowedAssetTypes = $this->allowedAssetTypes; } $maxSize = UploadedFile::getMaxFilesize(); if ($uploadedFile->getSize() > $maxSize) { throw new ApplicationException(Lang::get('cms::lang.asset.too_large', ['max_size ' => File::sizeToString($maxSize)])); } $ext = strtolower(pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_EXTENSION)); if (!in_array($ext, $allowedAssetTypes)) { throw new ApplicationException(Lang::get('cms::lang.asset.type_not_allowed', ['allowed_types' => implode(', ', $allowedAssetTypes)])); } if (!$uploadedFile->isValid()) { throw new ApplicationException(Lang::get('cms::lang.asset.file_not_valid')); } $uploadedFile->move($this->getCurrentPath(), $uploadedFile->getClientOriginalName()); die('success'); } catch (Exception $ex) { $message = $fileName !== null ? Lang::get('cms::lang.asset.error_uploading_file', ['name' => $fileName, 'error' => $ex->getMessage()]) : $ex->getMessage(); die($message); } }
public function indexAction(Request $request) { $configuration = []; $authenticationType = $this->container->getParameter('ilios_authentication.type'); $configuration['type'] = $authenticationType; if ($authenticationType == 'shibboleth') { $loginPath = $this->container->getParameter('ilios_authentication.shibboleth.login_path'); $url = $request->getSchemeAndHttpHost(); $configuration['loginUrl'] = $url . $loginPath; } if ($authenticationType === 'cas') { $cas = $this->container->get('ilios_authentication.cas.manager'); $configuration['casLoginUrl'] = $cas->getLoginUrl(); } $configuration['locale'] = $this->container->getParameter('locale'); $ldapUrl = $this->container->getParameter('ilios_core.ldap.url'); if (!empty($ldapUrl)) { $configuration['userSearchType'] = 'ldap'; } else { $configuration['userSearchType'] = 'local'; } $configuration['maxUploadSize'] = UploadedFile::getMaxFilesize(); $configuration['apiVersion'] = WebIndexFromJson::API_VERSION; $configuration['trackingEnabled'] = $this->container->getParameter('ilios_core.enable_tracking'); if ($configuration['trackingEnabled']) { $configuration['trackingCode'] = $this->container->getParameter('ilios_core.tracking_code'); } return new JsonResponse(array('config' => $configuration)); }
/** * Filters an array of files. * * This method created test instances of UploadedFile so that the move() * method can be called on those instances. * * If the size of a file is greater than the allowed size (from php.ini) then * an invalid UploadedFile is returned with an error set to UPLOAD_ERR_INI_SIZE. * * @see UploadedFile * * @param array $files An array of files * * @return array An array with all uploaded files marked as already moved */ protected function filterFiles(array $files) { $filtered = array(); foreach ($files as $key => $value) { if (is_array($value)) { $filtered[$key] = $this->filterFiles($value); } elseif ($value instanceof UploadedFile) { if ($value->isValid() && $value->getSize() > UploadedFile::getMaxFilesize()) { $filtered[$key] = new UploadedFile('', $value->getClientOriginalName(), $value->getClientMimeType(), 0, UPLOAD_ERR_INI_SIZE, true); } else { $filtered[$key] = new UploadedFile($value->getPathname(), $value->getClientOriginalName(), $value->getClientMimeType(), $value->getClientSize(), $value->getError(), true); } } } return $filtered; }
/** * {@inheritDoc} */ public function validate($value, Constraint $constraint) { if (null === $value || '' === $value) { return; } if ($value instanceof UploadedFile && !$value->isValid()) { switch ($value->getError()) { case UPLOAD_ERR_INI_SIZE: if ($constraint->maxSize) { if (ctype_digit((string) $constraint->maxSize)) { $maxSize = (int) $constraint->maxSize; } elseif (preg_match('/^\\d++k$/', $constraint->maxSize)) { $maxSize = $constraint->maxSize * 1024; } elseif (preg_match('/^\\d++M$/', $constraint->maxSize)) { $maxSize = $constraint->maxSize * 1048576; } else { throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); } $maxSize = min(UploadedFile::getMaxFilesize(), $maxSize); } else { $maxSize = UploadedFile::getMaxFilesize(); } $this->context->addViolation($constraint->uploadIniSizeErrorMessage, array('{{ limit }}' => $maxSize, '{{ suffix }}' => 'bytes')); return; case UPLOAD_ERR_FORM_SIZE: $this->context->addViolation($constraint->uploadFormSizeErrorMessage); return; case UPLOAD_ERR_PARTIAL: $this->context->addViolation($constraint->uploadPartialErrorMessage); return; case UPLOAD_ERR_NO_FILE: $this->context->addViolation($constraint->uploadNoFileErrorMessage); return; case UPLOAD_ERR_NO_TMP_DIR: $this->context->addViolation($constraint->uploadNoTmpDirErrorMessage); return; case UPLOAD_ERR_CANT_WRITE: $this->context->addViolation($constraint->uploadCantWriteErrorMessage); return; case UPLOAD_ERR_EXTENSION: $this->context->addViolation($constraint->uploadExtensionErrorMessage); return; default: $this->context->addViolation($constraint->uploadErrorMessage); return; } } if (!is_scalar($value) && !$value instanceof FileObject && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $path = $value instanceof FileObject ? $value->getPathname() : (string) $value; if (!is_file($path)) { $this->context->addViolation($constraint->notFoundMessage, array('{{ file }}' => $path)); return; } if (!is_readable($path)) { $this->context->addViolation($constraint->notReadableMessage, array('{{ file }}' => $path)); return; } if ($constraint->maxSize) { if (ctype_digit((string) $constraint->maxSize)) { $size = filesize($path); $limit = (int) $constraint->maxSize; $suffix = 'bytes'; } elseif (preg_match('/^\\d++k$/', $constraint->maxSize)) { $size = round(filesize($path) / 1000, 2); $limit = (int) $constraint->maxSize; $suffix = 'kB'; } elseif (preg_match('/^\\d++M$/', $constraint->maxSize)) { $size = round(filesize($path) / 1000000, 2); $limit = (int) $constraint->maxSize; $suffix = 'MB'; } else { throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); } if ($size > $limit) { $this->context->addViolation($constraint->maxSizeMessage, array('{{ size }}' => $size, '{{ limit }}' => $limit, '{{ suffix }}' => $suffix, '{{ file }}' => $path)); return; } } if ($constraint->mimeTypes) { if (!$value instanceof FileObject) { $value = new FileObject($value); } $mimeTypes = (array) $constraint->mimeTypes; $mime = $value->getMimeType(); $valid = false; foreach ($mimeTypes as $mimeType) { if ($mimeType === $mime) { $valid = true; break; } if ($discrete = strstr($mimeType, '/*', true)) { if (strstr($mime, '/', true) === $discrete) { $valid = true; break; } } } if (false === $valid) { $this->context->addViolation($constraint->mimeTypesMessage, array('{{ type }}' => '"' . $mime . '"', '{{ types }}' => '"' . implode('", "', $mimeTypes) . '"', '{{ file }}' => $path)); } } }
/** * Upload file from the request * * @param UploadedFile $file * @return Array $data Retrieve into the content of response * @throws BadRequestHttpException The file is too big */ private function doRequestUpload(UploadedFile $file) { $tmpDirectory = $this->getApplication()->getTemporaryDir(); $data = []; if (null !== $file) { if ($file->isValid()) { if ($file->getClientSize() <= $file->getMaxFilesize()) { $data = $this->buildData($file->getClientOriginalName(), $file->guessExtension()); $file->move($tmpDirectory, $data['filename']); $data['size'] = round($file->getClientSize() / 1024, 2); if ($imageInfo = @getimagesize($data['path'])) { if (isset($imageInfo[0]) && isset($imageInfo[1])) { $data['width'] = $imageInfo[0]; $data['height'] = $imageInfo[1]; } } else { $data['width'] = 0; $data['height'] = 0; } } else { throw new BadRequestHttpException('Too big file, the max file size is ' . $file->getMaxFilesize()); } } else { throw new BadRequestHttpException($file->getErrorMessage()); } } return $data; }
/** * @param UploadedFile $file * * @return array() */ private function getFileProperties($file) { $properties = array(); $properties['original_name'] = $file->getClientOriginalName(); $properties['extension'] = $file->guessExtension(); $properties['name'] = $this->getFileNameOrThumbnail($properties['original_name'], false); $properties['name_uid'] = $properties['original_name']; $properties['thumbnail_name'] = $this->getFileNameOrThumbnail($properties['original_name'], true); $properties['size'] = $file->getClientSize(); $properties['maxfilesize'] = $file->getMaxFilesize(); $properties['mimetype'] = $file->getMimeType(); $properties['session'] = $this->session->getId(); $properties['id_session'] = $this->id_session; $properties['temp_dir'] = $this->params['param_temp_path'] . '/' . $this->session->getId() . '/' . $properties['id_session']; return $properties; }
public function uploadedFileErrorProvider() { $tests = array(array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'), array(UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'), array(UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'), array(UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'), array(UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'), array(UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage')); if (class_exists('Symfony\\Component\\HttpFoundation\\File\\UploadedFile')) { $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => UploadedFile::getMaxFilesize() . ' bytes')); } return $tests; }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof File) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\File'); } if (null === $value || '' === $value) { return; } if ($value instanceof UploadedFile && !$value->isValid()) { switch ($value->getError()) { case UPLOAD_ERR_INI_SIZE: if ($constraint->maxSize) { if (ctype_digit((string) $constraint->maxSize)) { $limitInBytes = (int) $constraint->maxSize; } elseif (preg_match('/^\\d++k$/', $constraint->maxSize)) { $limitInBytes = $constraint->maxSize * self::KB_BYTES; } elseif (preg_match('/^\\d++M$/', $constraint->maxSize)) { $limitInBytes = $constraint->maxSize * self::MB_BYTES; } else { throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); } $limitInBytes = min(UploadedFile::getMaxFilesize(), $limitInBytes); } else { $limitInBytes = UploadedFile::getMaxFilesize(); } $this->context->addViolation($constraint->uploadIniSizeErrorMessage, array('{{ limit }}' => $limitInBytes, '{{ suffix }}' => 'bytes')); return; case UPLOAD_ERR_FORM_SIZE: $this->context->addViolation($constraint->uploadFormSizeErrorMessage); return; case UPLOAD_ERR_PARTIAL: $this->context->addViolation($constraint->uploadPartialErrorMessage); return; case UPLOAD_ERR_NO_FILE: $this->context->addViolation($constraint->uploadNoFileErrorMessage); return; case UPLOAD_ERR_NO_TMP_DIR: $this->context->addViolation($constraint->uploadNoTmpDirErrorMessage); return; case UPLOAD_ERR_CANT_WRITE: $this->context->addViolation($constraint->uploadCantWriteErrorMessage); return; case UPLOAD_ERR_EXTENSION: $this->context->addViolation($constraint->uploadExtensionErrorMessage); return; default: $this->context->addViolation($constraint->uploadErrorMessage); return; } } if (!is_scalar($value) && !$value instanceof FileObject && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $path = $value instanceof FileObject ? $value->getPathname() : (string) $value; if (!is_file($path)) { $this->context->addViolation($constraint->notFoundMessage, array('{{ file }}' => $path)); return; } if (!is_readable($path)) { $this->context->addViolation($constraint->notReadableMessage, array('{{ file }}' => $path)); return; } if ($constraint->maxSize) { $sizeInBytes = filesize($path); $limitInBytes = (int) $constraint->maxSize; if (preg_match('/^\\d++k$/', $constraint->maxSize)) { $limitInBytes *= self::KB_BYTES; } elseif (preg_match('/^\\d++M$/', $constraint->maxSize)) { $limitInBytes *= self::MB_BYTES; } elseif (!ctype_digit((string) $constraint->maxSize)) { throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); } if ($sizeInBytes > $limitInBytes) { // Convert the limit to the smallest possible number // (i.e. try "MB", then "kB", then "bytes") $coef = self::MB_BYTES; $limitAsString = (string) ($limitInBytes / $coef); // Restrict the limit to 2 decimals (without rounding! we // need the precise value) while (self::moreDecimalsThan($limitAsString, 2)) { $coef /= 1000; $limitAsString = (string) ($limitInBytes / $coef); } // Convert size to the same measure, but round to 2 decimals $sizeAsString = (string) round($sizeInBytes / $coef, 2); // If the size and limit produce the same string output // (due to rounding), reduce the coefficient while ($sizeAsString === $limitAsString) { $coef /= 1000; $limitAsString = (string) ($limitInBytes / $coef); $sizeAsString = (string) round($sizeInBytes / $coef, 2); } $this->context->addViolation($constraint->maxSizeMessage, array('{{ size }}' => $sizeAsString, '{{ limit }}' => $limitAsString, '{{ suffix }}' => static::$suffices[$coef], '{{ file }}' => $path)); return; } } if ($constraint->mimeTypes) { if (!$value instanceof FileObject) { $value = new FileObject($value); } $mimeTypes = (array) $constraint->mimeTypes; $mime = $value->getMimeType(); $valid = false; foreach ($mimeTypes as $mimeType) { if ($mimeType === $mime) { $valid = true; break; } if ($discrete = strstr($mimeType, '/*', true)) { if (strstr($mime, '/', true) === $discrete) { $valid = true; break; } } } if (false === $valid) { $this->context->addViolation($constraint->mimeTypesMessage, array('{{ type }}' => '"' . $mime . '"', '{{ types }}' => '"' . implode('", "', $mimeTypes) . '"', '{{ file }}' => $path)); } } }
/** * Product form * * @Template * @param int $id The product ID * @param Request $request * @return array Template vars */ public function formAction($id, Request $request) { $productAdapter = $this->container->get('prestashop.adapter.data_provider.product'); $product = $productAdapter->getProduct($id); if (!$product || empty($product->id)) { return $this->redirectToRoute('admin_product_catalog'); } $shopContext = $this->get('prestashop.adapter.shop.context'); $legacyContextService = $this->get('prestashop.adapter.legacy.context'); $legacyContext = $legacyContextService->getContext(); $isMultiShopContext = count($shopContext->getContextListShopID()) > 1 ? true : false; // Redirect to legacy controller (FIXME: temporary behavior) $pagePreference = $this->container->get('prestashop.core.admin.page_preference_interface'); /* @var $pagePreference AdminPagePreferenceInterface */ if ($pagePreference->getTemporaryShouldUseLegacyPage('product')) { $legacyUrlGenerator = $this->container->get('prestashop.core.admin.url_generator_legacy'); /* @var $legacyUrlGenerator UrlGeneratorInterface */ return $this->redirect($legacyUrlGenerator->generate('admin_product_form', array('id' => $id)), 302); } $response = new JsonResponse(); $modelMapper = new ProductAdminModelAdapter($product, $this->container->get('prestashop.adapter.legacy.context'), $this->container->get('prestashop.adapter.admin.wrapper.product'), $this->container->get('prestashop.adapter.tools'), $productAdapter, $this->container->get('prestashop.adapter.data_provider.supplier'), $this->container->get('prestashop.adapter.data_provider.warehouse'), $this->container->get('prestashop.adapter.data_provider.feature'), $this->container->get('prestashop.adapter.data_provider.pack'), $this->container->get('prestashop.adapter.shop.context')); $adminProductWrapper = $this->container->get('prestashop.adapter.admin.wrapper.product'); $form = $this->createFormBuilder($modelMapper->getFormData())->add('id_product', 'Symfony\\Component\\Form\\Extension\\Core\\Type\\HiddenType')->add('step1', 'PrestaShopBundle\\Form\\Admin\\Product\\ProductInformation')->add('step2', 'PrestaShopBundle\\Form\\Admin\\Product\\ProductPrice')->add('step3', 'PrestaShopBundle\\Form\\Admin\\Product\\ProductQuantity')->add('step4', 'PrestaShopBundle\\Form\\Admin\\Product\\ProductShipping')->add('step5', 'PrestaShopBundle\\Form\\Admin\\Product\\ProductSeo')->add('step6', 'PrestaShopBundle\\Form\\Admin\\Product\\ProductOptions')->getForm(); $formBulkCombinations = $this->createForm('PrestaShopBundle\\Form\\Admin\\Product\\ProductCombinationBulk', null, array('iso_code' => $this->get('prestashop.adapter.legacy.context')->getContext()->currency->iso_code, 'price_display_precision' => $this->configuration->get('_PS_PRICE_DISPLAY_PRECISION_'))); $form->handleRequest($request); $formData = $form->getData(); if ($form->isSubmitted()) { if ($form->isValid()) { // Legacy code. To fix when Object model will change. But report Hooks. $postData = $request->request->all(); $combinations = array(); foreach ((array) $postData as $postKey => $postValue) { if (preg_match('/^combination_.*/', $postKey)) { $combinations[$postKey] = $postValue; } } $formData['step3']['combinations'] = $combinations; //define POST values for keeping legacy adminController skills $_POST = $modelMapper->getModelData($formData, $isMultiShopContext) + $_POST; $_POST['state'] = \Product::STATE_SAVED; $adminProductController = $adminProductWrapper->getInstance(); $adminProductController->setIdObject($formData['id_product']); $adminProductController->setAction('save'); // Hooks: this will trigger legacy AdminProductController, postProcess(): // actionAdminSaveBefore; actionAdminProductsControllerSaveBefore // actionProductAdd or actionProductUpdate (from processSave() -> processAdd() or processUpdate()) // actionAdminSaveAfter; actionAdminProductsControllerSaveAfter if ($product = $adminProductController->postCoreProcess()) { $adminProductController->processSuppliers($product->id); $adminProductController->processFeatures($product->id); $adminProductController->processSpecificPricePriorities(); foreach ($_POST['combinations'] as $combinationValues) { $adminProductWrapper->processProductAttribute($product, $combinationValues); // For now, each attribute set the same value. $adminProductWrapper->processDependsOnStock($product, $_POST['depends_on_stock'] == '1', $combinationValues['id_product_attribute']); } $adminProductWrapper->processDependsOnStock($product, $_POST['depends_on_stock'] == '1'); // If there is no combination, then quantity is managed for the whole product (as combination ID 0) // In all cases, legacy hooks are triggered: actionProductUpdate and actionUpdateQuantity if (count($_POST['combinations']) === 0) { $adminProductWrapper->processQuantityUpdate($product, $_POST['qty_0']); } // else quantities are managed from $adminProductWrapper->processProductAttribute() above. $adminProductWrapper->processProductOutOfStock($product, $_POST['out_of_stock']); $adminProductWrapper->processProductCustomization($product, $_POST['custom_fields']); $adminProductWrapper->processAttachments($product, $_POST['attachments']); $adminProductController->processWarehouses(); $response->setData(['product' => $product]); } if ($request->isXmlHttpRequest()) { return $response; } } elseif ($request->isXmlHttpRequest()) { $response->setStatusCode(400); $response->setData($this->getFormErrorsForJS($form)); return $response; } } $stockManager = $this->container->get('prestashop.core.data_provider.stock_interface'); /* @var $stockManager StockInterface */ $warehouseProvider = $this->container->get('prestashop.adapter.data_provider.warehouse'); /* @var $warehouseProvider WarehouseDataProvider */ //If context shop is define to a group shop, disable the form if ($legacyContext->shop->getContext() == $shopContext->getShopContextGroupConstant()) { return $this->render('PrestaShopBundle:Admin/Product:formDisable.html.twig', ['showContentHeader' => false]); } // languages for switch dropdown $languages = $legacyContextService->getLanguages(); // generate url preview if ($product->active) { $preview_url = $adminProductWrapper->getPreviewUrl($product); $preview_url_deactive = $adminProductWrapper->getPreviewUrlDeactivate($preview_url); } else { $preview_url_deactive = $adminProductWrapper->getPreviewUrl($product, false); $preview_url = $adminProductWrapper->getPreviewUrlDeactivate($preview_url_deactive); } $attributeGroups = $this->getDoctrine()->getManager()->getRepository('PrestaShopBundle:Attribute')->findByLangAndShop(1, 1); return array('form' => $form->createView(), 'formCombinations' => $formBulkCombinations->createView(), 'categories' => $this->get('prestashop.adapter.data_provider.category')->getCategoriesWithBreadCrumb(), 'id_product' => $id, 'ids_product_attribute' => isset($formData['step3']['id_product_attributes']) ? implode(',', $formData['step3']['id_product_attributes']) : '', 'has_combinations' => isset($formData['step3']['id_product_attributes']) && count($formData['step3']['id_product_attributes']) > 0, 'combinations_count' => isset($formData['step3']['id_product_attributes']) ? count($formData['step3']['id_product_attributes']) : 0, 'asm_globally_activated' => $stockManager->isAsmGloballyActivated(), 'warehouses' => $stockManager->isAsmGloballyActivated() ? $warehouseProvider->getWarehouses() : [], 'is_multishop_context' => $isMultiShopContext, 'is_combination_active' => $this->get('prestashop.adapter.legacy.configuration')->combinationIsActive(), 'showContentHeader' => false, 'preview_link' => $preview_url, 'preview_link_deactivate' => $preview_url_deactive, 'stats_link' => $legacyContextService->getAdminLink('AdminStats', true, ['module' => 'statsproduct', 'id_product' => $id]), 'help_link' => $this->generateSidebarLink('AdminProducts'), 'languages' => $languages, 'default_language_iso' => $languages[0]['iso_code'], 'attribute_groups' => $attributeGroups, 'max_upload_size' => \Tools::formatBytes(UploadedFile::getMaxFilesize())); }
/** @test */ function it_gets_and_sets_max_upload_size() { $this->assertEquals($this->uploadService->maxUploadSize(), UploadedFile::getMaxFilesize()); $this->assertEquals($this->uploadService->validatesUploadedFile(50000), 50000); $this->assertEquals($this->uploadService->validatesUploadedFile(), 50000); }
/** * Get POST max file size * * @return integer */ private function getUploadMaxFileSize() { $postMaxSize = trim(ini_get('post_max_size')); if ('' === $postMaxSize) { $postMaxSize = PHP_INT_MAX; } switch (strtolower(substr($postMaxSize, -1))) { case 'g': $postMaxSize *= 1024; case 'm': $postMaxSize *= 1024; case 'k': $postMaxSize *= 1024; } return min(UploadedFile::getMaxFilesize(), (int) $postMaxSize); }
/** * Get POST max file size * * @return integer */ private function getUploadMaxFileSize() { $postMaxSize = trim(ini_get('post_max_size')); if ('' === $postMaxSize) { $postMaxSize = PHP_INT_MAX; } switch (strtolower(substr($postMaxSize, -1))) { /** @noinspection PhpMissingBreakStatementInspection */ case 'g': $postMaxSize *= 1024; /** @noinspection PhpMissingBreakStatementInspection */ /** @noinspection PhpMissingBreakStatementInspection */ case 'm': $postMaxSize *= 1024; case 'k': $postMaxSize *= 1024; } return min(UploadedFile::getMaxFilesize(), (int) $postMaxSize); }
/** * @param Symfony\Component\HttpFoundation\Request $request * * @return Symfony\Component\HttpFoundation\Response */ public function uploadAction(Request $request, $folderId = null) { $this->validateAccessForRole('ROLE_ACCESS_DOCUMENTS'); if (null !== $folderId && $folderId > 0) { $folder = $this->getService('em')->find('RZ\\Roadiz\\Core\\Entities\\Folder', (int) $folderId); $this->assignation['folder'] = $folder; } /* * Handle main form */ $form = $this->buildUploadForm($folderId); $form->handleRequest($request); if ($form->isValid()) { $document = $this->uploadDocument($form, $folderId); if (false !== $document) { $msg = $this->getTranslator()->trans('document.%name%.uploaded', ['%name%' => $document->getFilename()]); $this->publishConfirmMessage($request, $msg); return new Response(json_encode(['success' => true, 'documentId' => $document->getId(), 'thumbnail' => ['id' => $document->getId(), 'filename' => $document->getFilename(), 'thumbnail' => $document->getViewer()->getDocumentUrlByArray(AjaxDocumentsExplorerController::$thumbnailArray), 'html' => $this->getTwig()->render('widgets/documentSmallThumbnail.html.twig', ['document' => $document])]]), Response::HTTP_OK, ['content-type' => 'application/javascript']); } else { $msg = $this->getTranslator()->trans('document.cannot_persist'); $this->publishErrorMessage($request, $msg); return new Response(json_encode(["error" => $msg]), Response::HTTP_NOT_FOUND, ['content-type' => 'application/javascript']); } } $this->assignation['form'] = $form->createView(); $this->assignation['maxUploadSize'] = \Symfony\Component\HttpFoundation\File\UploadedFile::getMaxFilesize() / 1024 / 1024; return $this->render('documents/upload.html.twig', $this->assignation); }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!is_string($value) && !is_null($value)) { if (!$constraint instanceof X2File) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\X2File'); } if (null === $value || '' === $value) { return; } if ($value instanceof UploadedFile && !$value->isValid()) { switch ($value->getError()) { case UPLOAD_ERR_INI_SIZE: $iniLimitSize = UploadedFile::getMaxFilesize(); if ($constraint->maxSize && $constraint->maxSize < $iniLimitSize) { $limitInBytes = $constraint->maxSize; $binaryFormat = $constraint->binaryFormat; } else { $limitInBytes = $iniLimitSize; $binaryFormat = true; } list($sizeAsString, $limitAsString, $suffix) = $this->factorizeSizes(0, $limitInBytes, $binaryFormat); $this->buildViolation($constraint->uploadIniSizeErrorMessage)->setParameter('{{ limit }}', $limitAsString)->setParameter('{{ suffix }}', $suffix)->setCode(UPLOAD_ERR_INI_SIZE)->addViolation(); return; case UPLOAD_ERR_FORM_SIZE: $this->buildViolation($constraint->uploadFormSizeErrorMessage)->setCode(UPLOAD_ERR_FORM_SIZE)->addViolation(); return; case UPLOAD_ERR_PARTIAL: $this->buildViolation($constraint->uploadPartialErrorMessage)->setCode(UPLOAD_ERR_PARTIAL)->addViolation(); return; case UPLOAD_ERR_NO_FILE: $this->buildViolation($constraint->uploadNoFileErrorMessage)->setCode(UPLOAD_ERR_NO_FILE)->addViolation(); return; case UPLOAD_ERR_NO_TMP_DIR: $this->buildViolation($constraint->uploadNoTmpDirErrorMessage)->setCode(UPLOAD_ERR_NO_TMP_DIR)->addViolation(); return; case UPLOAD_ERR_CANT_WRITE: $this->buildViolation($constraint->uploadCantWriteErrorMessage)->setCode(UPLOAD_ERR_CANT_WRITE)->addViolation(); return; case UPLOAD_ERR_EXTENSION: $this->buildViolation($constraint->uploadExtensionErrorMessage)->setCode(UPLOAD_ERR_EXTENSION)->addViolation(); return; default: $this->buildViolation($constraint->uploadErrorMessage)->setCode($value->getError())->addViolation(); return; } } if (!is_scalar($value) && !$value instanceof FileObject && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $path = $value instanceof FileObject ? $value->getPathname() : (string) $value; if (!is_file($path)) { $this->buildViolation($constraint->notFoundMessage)->setParameter('{{ file }}', $this->formatValue($path))->setCode(X2File::NOT_FOUND_ERROR)->addViolation(); return; } if (!is_readable($path)) { $this->buildViolation($constraint->notReadableMessage)->setParameter('{{ file }}', $this->formatValue($path))->setCode(X2File::NOT_READABLE_ERROR)->addViolation(); return; } $sizeInBytes = filesize($path); if (0 === $sizeInBytes) { $this->buildViolation($constraint->disallowEmptyMessage)->setParameter('{{ file }}', $this->formatValue($path))->setCode(X2File::EMPTY_ERROR)->addViolation(); return; } if ($constraint->maxSize) { $limitInBytes = $constraint->maxSize; if ($sizeInBytes > $limitInBytes) { list($sizeAsString, $limitAsString, $suffix) = $this->factorizeSizes($sizeInBytes, $limitInBytes, $constraint->binaryFormat); $this->buildViolation($constraint->maxSizeMessage)->setParameter('{{ file }}', $this->formatValue($path))->setParameter('{{ size }}', $sizeAsString)->setParameter('{{ limit }}', $limitAsString)->setParameter('{{ suffix }}', $suffix)->setCode(X2File::TOO_LARGE_ERROR)->addViolation(); return; } } if ($constraint->mimeTypes) { if (!$value instanceof FileObject) { $value = new FileObject($value); } $mimeTypes = (array) $constraint->mimeTypes; $mime = $value->getMimeType(); foreach ($mimeTypes as $mimeType) { if ($mimeType === $mime) { return; } if ($discrete = strstr($mimeType, '/*', true)) { if (strstr($mime, '/', true) === $discrete) { return; } } } $this->buildViolation($constraint->mimeTypesMessage)->setParameter('{{ file }}', $this->formatValue($path))->setParameter('{{ type }}', $this->formatValue($mime))->setParameter('{{ types }}', $this->formatValues($mimeTypes))->setCode(X2File::INVALID_MIME_TYPE_ERROR)->addViolation(); } } }
/** * Upload file from the request * * @param UploadedFile $file * @return Array $data Retrieve into the content of response * @throws BadRequestHttpException The file is too big */ private function doRequestUpload(UploadedFile $file) { $tmpDirectory = $this->getParameter("kernel.cache_dir"); $data = []; if (null !== $file) { if ($file->isValid()) { if ($file->getClientSize() <= $file->getMaxFilesize()) { $data = $this->buildData($file->getClientOriginalName(), $file->guessExtension()); $file->move($tmpDirectory, $data['filename']); } else { throw new BadRequestHttpException('Too big file, the max file size is ' . $file->getMaxFilesize()); } } else { throw new BadRequestHttpException($file->getErrorMessage()); } } return $data; }
/** * @brief Process the upload request. */ protected function handleUpload(Request $request) { global $MODDIR; global $SYSCONFDIR; define("UPLOAD_ERR_EMPTY", 5); define("UPLOAD_ERR_INVALID_FOLDER_PK", 100); define("UPLOAD_ERR_RESEND", 200); $uploadErrors = array(UPLOAD_ERR_OK => _("No errors."), UPLOAD_ERR_INI_SIZE => _("Larger than upload_max_filesize ") . ini_get('upload_max_filesize'), UPLOAD_ERR_FORM_SIZE => _("Larger than form MAX_FILE_SIZE."), UPLOAD_ERR_PARTIAL => _("Partial upload."), UPLOAD_ERR_NO_FILE => _("No file selected."), UPLOAD_ERR_NO_TMP_DIR => _("No temporary directory."), UPLOAD_ERR_CANT_WRITE => _("Can't write to disk."), UPLOAD_ERR_EXTENSION => _("File upload stopped by extension."), UPLOAD_ERR_EMPTY => _("File is empty or you don't have permission to read the file."), UPLOAD_ERR_INVALID_FOLDER_PK => _("Invalid Folder."), UPLOAD_ERR_RESEND => _("This seems to be a resent file.")); $folderId = intval($request->get(self::FOLDER_PARAMETER_NAME)); $description = stripslashes($request->get(self::DESCRIPTION_INPUT_NAME)); $description = $this->basicShEscaping($description); $uploadedFile = $request->files->get(self::FILE_INPUT_NAME); if ($uploadedFile === null) { return array(false, $uploadErrors[UPLOAD_ERR_NO_FILE], $description); } if ($request->getSession()->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME) != $request->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME)) { return array(false, $uploadErrors[UPLOAD_ERR_RESEND], $description); } if ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) { return array(false, $uploadErrors[UPLOAD_ERR_EMPTY], $description); } else { if ($uploadedFile->getSize() >= UploadedFile::getMaxFilesize()) { return array(false, $uploadErrors[UPLOAD_ERR_INI_SIZE] . _(" is really ") . $uploadedFile->getSize() . " bytes.", $description); } } if (empty($folderId)) { return array(false, $uploadErrors[UPLOAD_ERR_INVALID_FOLDER_PK], $description); } if (!$uploadedFile->isValid()) { return array(false, $uploadedFile->getErrorMessage(), $description); } $originalFileName = $uploadedFile->getClientOriginalName(); $originalFileName = $this->basicShEscaping($originalFileName); $public = $request->get('public'); $publicPermission = $public == self::PUBLIC_ALL ? Auth::PERM_READ : Auth::PERM_NONE; /* Create an upload record. */ $uploadMode = 1 << 3; // code for "it came from web upload" $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $uploadId = JobAddUpload($userId, $groupId, $originalFileName, $originalFileName, $description, $uploadMode, $folderId, $publicPermission); if (empty($uploadId)) { return array(false, _("Failed to insert upload record"), $description); } try { $uploadedTempFile = $uploadedFile->move($uploadedFile->getPath(), $uploadedFile->getFilename() . '-uploaded')->getPathname(); } catch (FileException $e) { return array(false, _("Could not save uploaded file"), $description); } $projectGroup = $GLOBALS['SysConf']['DIRECTORIES']['PROJECTGROUP'] ?: 'fossy'; $wgetAgentCall = "{$MODDIR}/wget_agent/agent/wget_agent -C -g {$projectGroup} -k {$uploadId} '{$uploadedTempFile}' -c '{$SYSCONFDIR}'"; $wgetOutput = array(); exec($wgetAgentCall, $wgetOutput, $wgetReturnValue); unlink($uploadedTempFile); if ($wgetReturnValue != 0) { $message = implode(' ', $wgetOutput); if (empty($message)) { $message = _("File upload failed. Error:") . $wgetReturnValue; } return array(false, $message, $description); } $message = $this->postUploadAddJobs($request, $originalFileName, $uploadId); return array(true, $message, $description); }
/** * Returns the maximum size of an uploaded file as configured in php.ini. * * @return int The maximum size of an uploaded file in bytes */ public function getMaxFilesize() { return UploadedFile::getMaxFilesize(); }
/** * Returns an informative upload error message. * * Copied from UploadedFile because its only public since 2.4 * * @param UploadedFile $file The file with the error. * * @return string The error message regarding the specified error code */ private function getErrorMessage(UploadedFile $file) { $errorCode = $file->getError(); static $errors = array(UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d kb).', UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', UPLOAD_ERR_NO_FILE => 'No file was uploaded.', UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.'); $maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? $file->getMaxFilesize() / 1024 : 0; $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.'; return sprintf($message, $file->getClientOriginalName(), $maxFilesize); }
public function uploadedFileErrorProvider() { $tests = array(array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'), array(UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'), array(UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'), array(UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'), array(UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'), array(UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage')); if (class_exists('Symfony\\Component\\HttpFoundation\\File\\UploadedFile')) { // when no maxSize is specified on constraint, it should use the ini value $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => UploadedFile::getMaxFilesize(), '{{ suffix }}' => 'bytes')); // it should use the smaller limitation (maxSize option in this case) $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => 1, '{{ suffix }}' => 'bytes'), '1'); // it correctly parses the maxSize option and not only uses simple string comparison // 1000M should be bigger than the ini value $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => UploadedFile::getMaxFilesize(), '{{ suffix }}' => 'bytes'), '1000M'); } return $tests; }
private function uploadFile($content) { $pic1 = base_path() . '/public/upload/' . md5(uniqid()) . '.jpg'; file_put_contents($pic1, base64_decode($content)); $imageInfo = getimagesize($pic1); if (strpos($imageInfo['mime'], 'image') === false) { return ''; } $fileSize = filesize($pic1); if ($fileSize > UploadedFile::getMaxFilesize()) { unlink($pic1); return ''; } return $pic1; }
public function uploadedFileErrorProvider() { return array(array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => UploadedFile::getMaxFilesize() . ' bytes')), array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'), array(UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'), array(UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'), array(UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'), array(UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'), array(UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage')); }
/** * Returns the maximum size of an uploaded file as configured in php.ini * @return int The maximum size of an uploaded file in kilobytes */ public static function getMaxFilesize() { return round(UploadedFile::getMaxFilesize() / 1024); }
/** * Checks if the passed value is valid. * * @param mixed $value The value that should be validated * @param Constraint $constraint The constraint for the validation * * @return Boolean Whether or not the value is valid * * @api */ public function isValid($value, Constraint $constraint) { if (null === $value || '' === $value) { return true; } if ($value instanceof UploadedFile && !$value->isValid()) { switch ($value->getError()) { case UPLOAD_ERR_INI_SIZE: $maxSize = UploadedFile::getMaxFilesize(); $maxSize = $constraint->maxSize ? min($maxSize, $constraint->maxSize) : $maxSize; $this->setMessage($constraint->uploadIniSizeErrorMessage, array('{{ limit }}' => $maxSize . ' bytes')); return false; case UPLOAD_ERR_FORM_SIZE: $this->setMessage($constraint->uploadFormSizeErrorMessage); return false; default: $this->setMessage($constraint->uploadErrorMessage); return false; } } if (!is_scalar($value) && !$value instanceof FileObject && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $path = $value instanceof FileObject ? $value->getPathname() : (string) $value; if (!file_exists($path)) { $this->setMessage($constraint->notFoundMessage, array('{{ file }}' => $path)); return false; } if (!is_readable($path)) { $this->setMessage($constraint->notReadableMessage, array('{{ file }}' => $path)); return false; } if ($constraint->maxSize) { if (ctype_digit((string) $constraint->maxSize)) { $size = filesize($path); $limit = $constraint->maxSize; $suffix = ' bytes'; } elseif (preg_match('/^(\\d+)k$/', $constraint->maxSize, $matches)) { $size = round(filesize($path) / 1000, 2); $limit = $matches[1]; $suffix = ' kB'; } elseif (preg_match('/^(\\d+)M$/', $constraint->maxSize, $matches)) { $size = round(filesize($path) / 1000000, 2); $limit = $matches[1]; $suffix = ' MB'; } else { throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); } if ($size > $limit) { $this->setMessage($constraint->maxSizeMessage, array('{{ size }}' => $size . $suffix, '{{ limit }}' => $limit . $suffix, '{{ file }}' => $path)); return false; } } if ($constraint->mimeTypes) { if (!$value instanceof FileObject) { $value = new FileObject($value); } if (!in_array($value->getMimeType(), (array) $constraint->mimeTypes)) { $this->setMessage($constraint->mimeTypesMessage, array('{{ type }}' => '"' . $value->getMimeType() . '"', '{{ types }}' => '"' . implode('", "', (array) $constraint->mimeTypes) . '"', '{{ file }}' => $path)); return false; } } return true; }
public function uploadedFileErrorProvider() { return array(array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => UploadedFile::getMaxFilesize() . ' bytes')), array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'), array(UPLOAD_ERR_PARTIAL, 'uploadErrorMessage'), array(UPLOAD_ERR_NO_TMP_DIR, 'uploadErrorMessage'), array(UPLOAD_ERR_EXTENSION, 'uploadErrorMessage')); }