public function execute(Request $request, Config $config, WorkingFolder $workingFolder, ResizedImageRepository $resizedImageRepository, CacheManager $cache) { $fileName = (string) $request->query->get('fileName'); list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size')); $downloadedFile = new DownloadedFile($fileName, $this->app); $downloadedFile->isValid(); if (!Image::isSupportedExtension(pathinfo($fileName, PATHINFO_EXTENSION), $config->get('thumbnails.bmpSupported'))) { throw new InvalidExtensionException('Unsupported image type or not image file'); } Utils::removeSessionCacheHeaders(); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($downloadedFile->getTimestamp()) . "-" . dechex($downloadedFile->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($downloadedFile->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $imagePreviewCacheExpires = (int) $config->get('cache.imagePreview'); if ($imagePreviewCacheExpires > 0) { $response->setMaxAge($imagePreviewCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $imagePreviewCacheExpires . 'seconds'); $response->setExpires($expireTime); } $cachedInfoPath = Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName); $cachedInfo = $cache->get($cachedInfoPath); $resultImage = null; // Try to reuse existing resized image if ($cachedInfo && isset($cachedInfo['width']) && isset($cachedInfo['height'])) { // Fix received aspect ratio $size = Image::calculateAspectRatio($requestedWidth, $requestedHeight, $cachedInfo['width'], $cachedInfo['height']); $resizedImage = $resizedImageRepository->getResizedImageBySize($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $size['width'], $size['height']); if ($resizedImage) { $resultImage = Image::create($resizedImage->getImageData()); } } // Fallback - get and resize the original image if (null === $resultImage) { $resultImage = Image::create($downloadedFile->getContents(), $config->get('thumbnails.bmpSupported')); $cache->set($cachedInfoPath, $resultImage->getInfo()); $resultImage->resize($requestedWidth, $requestedHeight); } $mimeType = $resultImage->getMimeType(); if (in_array($mimeType, array('image/bmp', 'image/x-ms-bmp'))) { $mimeType = 'image/jpeg'; // Image::getData() by default converts resized images to JPG } $response->headers->set('Content-Type', $mimeType . '; name="' . $downloadedFile->getFileName() . '"'); $response->setContent($resultImage->getData()); return $response; }
public function execute(Request $request, WorkingFolder $workingFolder, Config $config, CacheManager $cache) { $fileName = (string) $request->get('fileName'); if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } if (!Image::isSupportedExtension(pathinfo($fileName, PATHINFO_EXTENSION))) { throw new InvalidNameException('Invalid source file name'); } if (!$workingFolder->containsFile($fileName)) { throw new FileNotFoundException(); } $cachePath = Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName); $imageInfo = array(); $cachedInfo = $cache->get($cachePath); if ($cachedInfo && isset($cachedInfo['width']) && isset($cachedInfo['height'])) { $imageInfo = $cachedInfo; } else { $file = new DownloadedFile($fileName, $this->app); if ($file->isValid()) { $image = Image::create($file->getContents()); $imageInfo = $image->getInfo(); $cache->set($cachePath, $imageInfo); } } return $imageInfo; }
/** * @param ResourceType $sourceFileResourceType * @param string $sourceFilePath * @param string $sourceFileName * @param int $width * @param int $height * * @return ResizedImage|null */ public function getResizedImageBySize(ResourceType $sourceFileResourceType, $sourceFilePath, $sourceFileName, $width, $height) { $resizedImagesPath = Path::combine($sourceFileResourceType->getDirectory(), $sourceFilePath, ResizedImage::DIR, $sourceFileName); $backend = $sourceFileResourceType->getBackend(); if (!$backend->hasDirectory($resizedImagesPath)) { return null; } $resizedImagesFiles = array_filter($backend->listContents($resizedImagesPath), function ($v) { return isset($v['type']) && $v['type'] === 'file'; }); $thresholdPixels = $this->config->get('images.threshold.pixels'); $thresholdPercent = (double) $this->config->get('images.threshold.percent') / 100; foreach ($resizedImagesFiles as $resizedImage) { $resizedImageSize = ResizedImage::getSizeFromFilename($resizedImage['basename']); $resizedImageWidth = $resizedImageSize['width']; $resizedImageHeight = $resizedImageSize['height']; if ($resizedImageWidth >= $width && ($resizedImageWidth <= $width + $thresholdPixels || $resizedImageWidth <= $width + $width * $thresholdPercent) && $resizedImageHeight >= $height && ($resizedImageHeight <= $height + $thresholdPixels || $resizedImageHeight <= $height + $height * $thresholdPercent)) { $resizedImage = new ResizedImage($this, $sourceFileResourceType, $sourceFilePath, $sourceFileName, $resizedImageWidth, $resizedImageHeight); if ($resizedImage->exists()) { $resizedImage->load(); return $resizedImage; } } } return null; }
public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository) { if (!$config->get('thumbnails.enabled')) { throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED); } $fileName = $request->get('fileName'); $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) { throw new InvalidNameException('Invalid source file name'); } if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } list($requestedWidth, $requestedHeight) = Image::parseSize($request->get('size')); $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight); /** * This was added on purpose to reset any Cache-Control headers set * for example by session_start(). Symfony Session has a workaround, * but but we can't rely on this as application may not use Symfony * components to handle sessions. */ header('Cache-Control:'); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($thumbnail->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails'); if ($thumbnailsCacheExpires > 0) { $response->setMaxAge($thumbnailsCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds'); $response->setExpires($expireTime); } $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"'); $response->setContent($thumbnail->getImageData()); return $response; }
public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository) { if (!$config->get('thumbnails.enabled')) { throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED); } $fileName = (string) $request->get('fileName'); $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) { throw new InvalidNameException('Invalid source file name'); } if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } if (!$workingFolder->containsFile($fileName)) { throw new FileNotFoundException(); } list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size')); $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight); Utils::removeSessionCacheHeaders(); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($thumbnail->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails'); if ($thumbnailsCacheExpires > 0) { $response->setMaxAge($thumbnailsCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds'); $response->setExpires($expireTime); } $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"'); $response->setContent($thumbnail->getImageData()); return $response; }
public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ResizedImageRepository $resizedImageRepository) { $fileName = $request->get('fileName'); if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!Image::isSupportedExtension($ext)) { throw new InvalidNameException('Invalid source file name'); } list($requestedWidth, $requestedHeight) = Image::parseSize($request->get('size')); $resizedImage = $resizedImageRepository->getResizedImage($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight); return array('url' => $resizedImage->getUrl()); }
public function execute(WorkingFolder $workingFolder, Request $request, Config $config) { $fileName = $request->get('fileName'); $thumbnail = $request->get('thumbnail'); $fileNames = (array) $request->get('fileNames'); if (!empty($fileNames)) { $urls = array(); foreach ($fileNames as $fileName) { if (!File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException(sprintf('Invalid file name: %s', $fileName)); } $urls[$fileName] = $workingFolder->getFileUrl($fileName); } return array('urls' => $urls); } if (!File::isValidName($fileName, $config->get('disallowUnsafeCharacters')) || $thumbnail && !File::isValidName($thumbnail, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } if (!$workingFolder->containsFile($fileName)) { throw new FileNotFoundException(); } return array('url' => $workingFolder->getFileUrl($thumbnail ? Path::combine(ResizedImage::DIR, $fileName, $thumbnail) : $fileName)); }
/** * Returns backend object for given private directory identifier * * @param string $privateDirIdentifier * * @return Backend */ public function getPrivateDirBackend($privateDirIdentifier) { $privateDirConfig = $this->config->get('privateDir'); if (!array_key_exists($privateDirIdentifier, $privateDirConfig)) { throw new \InvalidArgumentException(sprintf('Private dir with identifier %s not found. Please check configuration file.', $privateDirIdentifier)); } $privateDir = $privateDirConfig[$privateDirIdentifier]; $backend = null; if (is_array($privateDir) && array_key_exists('backend', $privateDir)) { $backend = $this->getBackend($privateDir['backend']); } else { $backend = $this->getBackend($privateDirConfig['backend']); } // Create a default .htaccess to disable access to current private directory $privateDirPath = $this->config->getPrivateDirPath($privateDirIdentifier); $htaccessPath = Path::combine($privateDirPath, '.htaccess'); if (!$backend->has($htaccessPath)) { $backend->write($htaccessPath, "Order Deny,Allow\nDeny from all\n"); } return $backend; }
public function execute(Request $request, WorkingFolder $workingFolder, ResizedImageRepository $resizedImageRepository, Config $config, CacheManager $cache) { $fileName = $request->get('fileName'); $sizes = $request->get('sizes'); $ext = pathinfo($fileName, PATHINFO_EXTENSION); if (!Image::isSupportedExtension($ext)) { throw new InvalidRequestException('Invalid file extension'); } if ($sizes) { $sizes = explode(',', $sizes); if (array_diff($sizes, array_keys($config->get('images.sizes')))) { throw new InvalidRequestException(sprintf('Invalid size requested (%s)', $request->get('sizes'))); } } $data = array(); $cachedInfo = $cache->get(Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName)); if ($cachedInfo && isset($cachedInfo['width']) && isset($cachedInfo['height'])) { $data['originalSize'] = sprintf("%dx%d", $cachedInfo['width'], $cachedInfo['height']); } $resizedImages = $resizedImageRepository->getResizedImagesList($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $sizes ?: array()); $data['resized'] = $resizedImages; return $data; }
/** * Returns a URL to a file. * * If the useProxyCommand option is set for a backend, the returned * URL will point to the CKFinder connector Proxy command. * * @param ResourceType $resourceType the file resource type * @param string $folderPath the resource-type relative folder path * @param string $fileName the file name * @param string|null $thumbnailFileName the thumbnail file name - if the file is a thumbnail * * @return string|null URL to a file or `null` if the backend does not support it. */ public function getFileUrl(ResourceType $resourceType, $folderPath, $fileName, $thumbnailFileName = null) { if (isset($this->backendConfig['useProxyCommand'])) { $connectorUrl = $this->app->getConnectorUrl(); $queryParameters = array('command' => 'Proxy', 'type' => $resourceType->getName(), 'currentFolder' => $folderPath, 'fileName' => $fileName); if ($thumbnailFileName) { $queryParameters['thumbnail'] = $thumbnailFileName; } $proxyCacheLifetime = (int) $this->ckConfig->get('cache.proxyCommand'); if ($proxyCacheLifetime > 0) { $queryParameters['cache'] = $proxyCacheLifetime; } return $connectorUrl . '?' . http_build_query($queryParameters, '', '&'); } $path = $thumbnailFileName ? Path::combine($resourceType->getDirectory(), $folderPath, ResizedImage::DIR, $fileName, $thumbnailFileName) : Path::combine($resourceType->getDirectory(), $folderPath, $fileName); if (isset($this->backendConfig['baseUrl'])) { return Path::combine($this->backendConfig['baseUrl'], Utils::encodeURLParts($path)); } $baseAdapter = $this->getBaseAdapter(); if (method_exists($baseAdapter, 'getFileUrl')) { return $baseAdapter->getFileUrl($path); } return null; }
public function execute(Request $request, Acl $acl, Config $config, ResourceTypeFactory $resourceTypeFactory) { $data = new \stdClass(); /** * Connector is always enabled here * * @see CKFinder::checkAuth() */ $data->enabled = true; $ln = ''; $lc = str_replace('-', '', ($config->get('licenseKey') ?: $config->get('LicenseKey')) . ' '); $pos = strpos(CKFinder::CHARS, $lc[2]) % 5; if ($pos == 1 || $pos == 2) { $ln = $config->get('licenseName') ?: $config->get('LicenseName'); } $data->s = $ln; $data->c = trim($lc[1] . $lc[8] . $lc[17] . $lc[22] . $lc[3] . $lc[13] . $lc[11] . $lc[20] . $lc[5] . $lc[24] . $lc[27]); // Thumbnails $thumbnailsConfig = $config->get('thumbnails'); $thumbnailsEnabled = (bool) $thumbnailsConfig['enabled']; if ($thumbnailsEnabled) { $sizes = array(); foreach ($thumbnailsConfig['sizes'] as $sizeInfo) { $sizes[] = sprintf("%dx%d", $sizeInfo['width'], $sizeInfo['height']); } $data->thumbs = $sizes; } // Images $imagesConfig = $config->get('images'); $images = array('max' => $imagesConfig['maxWidth'] . 'x' . $imagesConfig['maxHeight']); if (isset($imagesConfig['sizes'])) { $resize = array(); foreach ($imagesConfig['sizes'] as $name => $sizeInfo) { $resize[$name] = $sizeInfo['width'] . 'x' . $sizeInfo['height']; } $images['sizes'] = $resize; } $data->images = $images; $resourceTypesNames = $config->getDefaultResourceTypes() ?: $config->getResourceTypes(); $data->resourceTypes = array(); if (!empty($resourceTypesNames)) { $phpMaxSize = 0; $maxUpload = Utils::returnBytes(ini_get('upload_max_filesize')); if ($maxUpload) { $phpMaxSize = $maxUpload; } $maxPost = Utils::returnBytes(ini_get('post_max_size')); if ($maxPost) { $phpMaxSize = $phpMaxSize ? min($phpMaxSize, $maxPost) : $maxPost; } //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" $memoryLimit = Utils::returnBytes(@ini_get('memory_limit')); if ($memoryLimit && $memoryLimit != -1) { $phpMaxSize = $phpMaxSize ? min($phpMaxSize, $memoryLimit) : $memoryLimit; } $data->uploadMaxSize = $phpMaxSize; $data->uploadCheckImages = !$config->get('checkSizeAfterScaling'); $requestedType = (string) $request->query->get('type'); foreach ($resourceTypesNames as $resourceTypeName) { if ($requestedType && $requestedType !== $resourceTypeName) { continue; } $aclMask = $acl->getComputedMask($resourceTypeName, '/'); if (!(Permission::FOLDER_VIEW & $aclMask)) { continue; } $resourceType = $resourceTypeFactory->getResourceType($resourceTypeName); $resourceTypeObject = array('name' => $resourceTypeName, 'allowedExtensions' => implode(",", $resourceType->getAllowedExtensions()), 'deniedExtensions' => implode(",", $resourceType->getDeniedExtensions()), 'hash' => $resourceType->getHash(), 'acl' => $aclMask, 'maxSize' => $resourceType->getMaxSize() ? min($resourceType->getMaxSize(), $phpMaxSize) : $phpMaxSize); $resourceTypeBackend = $resourceType->getBackend(); if ($resourceType->isLazyLoaded()) { $resourceTypeObject['hasChildren'] = false; $resourceTypeObject['lazyLoad'] = true; } else { $resourceTypeObject['hasChildren'] = $resourceTypeBackend->containsDirectories($resourceType, $resourceType->getDirectory()); } if ($label = $resourceType->getLabel()) { $resourceTypeObject['label'] = $label; } $useProxyCommand = $resourceTypeBackend->usesProxyCommand(); if ($useProxyCommand) { $resourceTypeObject['useProxyCommand'] = true; } else { $baseUrl = $resourceTypeBackend->getBaseUrl(); if ($baseUrl) { $resourceTypeObject['url'] = rtrim(Path::combine($baseUrl, $resourceType->getDirectory()), '/') . '/'; } } $trackedOperations = $resourceTypeBackend->getTrackedOperations(); if (!empty($trackedOperations)) { $resourceTypeObject['trackedOperations'] = $trackedOperations; } $data->resourceTypes[] = $resourceTypeObject; } } $enabledPlugins = $config->get('plugins'); if (!empty($enabledPlugins)) { $data->plugins = $enabledPlugins; } $proxyCacheLifetime = (int) $config->get('cache.proxyCommand'); if ($proxyCacheLifetime) { $data->proxyCache = $proxyCacheLifetime; } return $data; }
public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, CacheManager $cache, ResizedImageRepository $resizedImageRepository, ThumbnailRepository $thumbnailRepository, Acl $acl, Config $config) { $fileName = (string) $request->query->get('fileName'); $editedImage = new EditedImage($fileName, $this->app); $saveAsNew = false; if (!$editedImage->exists()) { $saveAsNew = true; $editedImage->saveAsNew(true); } else { // If file exists check for FILE_DELETE permission $resourceTypeName = $workingFolder->getResourceType()->getName(); $path = $workingFolder->getClientCurrentFolder(); if (!$acl->isAllowed($resourceTypeName, $path, Permission::FILE_DELETE)) { throw new UnauthorizedException(sprintf('Unauthorized: no FILE_DELETE permission in %s:%s', $resourceTypeName, $path)); } } if (!Image::isSupportedExtension($editedImage->getExtension())) { throw new InvalidExtensionException('Unsupported image type or not image file'); } $imageFormat = Image::mimeTypeFromExtension($editedImage->getExtension()); $uploadedData = (string) $request->request->get('content'); if (null === $uploadedData || strpos($uploadedData, 'data:image/png;base64,') !== 0) { throw new InvalidUploadException('Invalid upload. Expected base64 encoded PNG image.'); } $data = explode(',', $uploadedData); $data = isset($data[1]) ? base64_decode($data[1]) : false; if (!$data) { throw new InvalidUploadException(); } try { $uploadedImage = Image::create($data); } catch (\Exception $e) { // No need to check if secureImageUploads is enabled - image must be valid here throw new InvalidUploadException('Invalid upload: corrupted image', Error::UPLOADED_CORRUPT, array(), $e); } $imagesConfig = $config->get('images'); if ($imagesConfig['maxWidth'] && $uploadedImage->getWidth() > $imagesConfig['maxWidth'] || $imagesConfig['maxHeight'] && $uploadedImage->getHeight() > $imagesConfig['maxHeight']) { $uploadedImage->resize($imagesConfig['maxWidth'], $imagesConfig['maxHeight'], $imagesConfig['quality']); } $editedImage->setNewContents($uploadedImage->getData($imageFormat)); $editedImage->setNewDimensions($uploadedImage->getWidth(), $uploadedImage->getHeight()); if (!$editedImage->isValid()) { throw new InvalidUploadException('Invalid file provided'); } $editFileEvent = new EditFileEvent($this->app, $editedImage); $imageInfo = $uploadedImage->getInfo(); $cache->set(Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName), $uploadedImage->getInfo()); $dispatcher->dispatch(CKFinderEvent::SAVE_IMAGE, $editFileEvent); $saved = false; if (!$editFileEvent->isPropagationStopped()) { $saved = $editedImage->save($editFileEvent->getNewContents()); if (!$saved) { throw new AccessDeniedException("Couldn't save image file"); } //Remove thumbnails and resized images in case if file is overwritten if (!$saveAsNew && $saved) { $resourceType = $workingFolder->getResourceType(); $thumbnailRepository->deleteThumbnails($resourceType, $workingFolder->getClientCurrentFolder(), $fileName); $resizedImageRepository->deleteResizedImages($resourceType, $workingFolder->getClientCurrentFolder(), $fileName); } } return array('saved' => (int) $saved, 'date' => Utils::formatDate(time()), 'size' => Utils::formatSize($imageInfo['size'])); }
public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, Config $config) { $fileName = (string) $request->query->get('fileName'); $thumbnailFileName = (string) $request->query->get('thumbnail'); if (!File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException(sprintf('Invalid file name: %s', $fileName)); } $cacheLifetime = (int) $request->query->get('cache'); if (!$workingFolder->containsFile($fileName)) { throw new FileNotFoundException(); } if ($thumbnailFileName) { if (!File::isValidName($thumbnailFileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException(sprintf('Invalid resized image file name: %s', $fileName)); } if (!$workingFolder->getResourceType()->isAllowedExtension(pathinfo($thumbnailFileName, PATHINFO_EXTENSION))) { throw new InvalidExtensionException(); } $resizedImageRespository = $this->app->getResizedImageRepository(); $file = $resizedImageRespository->getExistingResizedImage($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $thumbnailFileName); $dataStream = $file->readStream(); } else { $file = new DownloadedFile($fileName, $this->app); $file->isValid(); $dataStream = $workingFolder->readStream($file->getFilename()); } $proxyDownload = new ProxyDownloadEvent($this->app, $file); $dispatcher->dispatch(CKFinderEvent::PROXY_DOWNLOAD, $proxyDownload); if ($proxyDownload->isPropagationStopped()) { throw new AccessDeniedException(); } $response = new StreamedResponse(); $response->headers->set('Content-Type', $file->getMimeType()); $response->headers->set('Content-Length', $file->getSize()); $response->headers->set('Content-Disposition', 'inline; filename="' . $fileName . '"'); if ($cacheLifetime > 0) { Utils::removeSessionCacheHeaders(); $response->setPublic(); $response->setEtag(dechex($file->getTimestamp()) . "-" . dechex($file->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($file->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $response->setMaxAge($cacheLifetime); $expireTime = new \DateTime(); $expireTime->modify('+' . $cacheLifetime . 'seconds'); $response->setExpires($expireTime); } $chunkSize = 1024 * 100; $response->setCallback(function () use($dataStream, $chunkSize) { if ($dataStream === false) { return false; } while (!feof($dataStream)) { echo fread($dataStream, $chunkSize); flush(); @set_time_limit(8); } return true; }); return $response; }
/** * Returns information about bitmap support for thumbnails. If bitmap * support is disabled, thumbnails for bitmaps will not be generated. * * @return bool `true` if bitmap support is enabled. */ public function isBitmapSupportEnabled() { return $this->config->get('thumbnails.bmpSupported'); }
public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, Config $config, CacheManager $cache, ThumbnailRepository $thumbsRepository) { // #111 IE9 download JSON issue workaround if ($request->get('asPlainText')) { $uploadEvents = array(CKFinderEvent::AFTER_COMMAND_FILE_UPLOAD, CKFinderEvent::AFTER_COMMAND_QUICK_UPLOAD); foreach ($uploadEvents as $eventName) { $dispatcher->addListener($eventName, function (AfterCommandEvent $event) { $response = $event->getResponse(); $response->headers->set('Content-Type', 'text/plain'); }); } } $uploaded = 0; $warningErrorCode = null; $upload = $request->files->get('upload'); if (null === $upload) { throw new InvalidUploadException(); } $uploadedFile = new UploadedFile($upload, $this->app); if (!$uploadedFile->isValid()) { throw new InvalidUploadException($uploadedFile->getErrorMessage()); } $uploadedFile->sanitizeFilename(); if ($uploadedFile->wasRenamed()) { $warningErrorCode = Error::UPLOADED_INVALID_NAME_RENAMED; } if (!$uploadedFile->hasValidFilename() || $uploadedFile->isHiddenFile()) { throw new InvalidNameException(); } if (!$uploadedFile->hasAllowedExtension()) { throw new InvalidExtensionException(); } // Autorename if required $overwriteOnUpload = $config->get('overwriteOnUpload'); if (!$overwriteOnUpload && $uploadedFile->autorename()) { $warningErrorCode = Error::UPLOADED_FILE_RENAMED; } $fileName = $uploadedFile->getFilename(); if (!$uploadedFile->isAllowedHtmlFile() && $uploadedFile->containsHtml()) { throw new InvalidUploadException('HTML detected in disallowed file type', Error::UPLOADED_WRONG_HTML_FILE); } if ($config->get('secureImageUploads') && $uploadedFile->isImage() && !$uploadedFile->isValidImage()) { throw new InvalidUploadException('Invalid upload: corrupted image', Error::UPLOADED_CORRUPT); } $maxFileSize = $workingFolder->getResourceType()->getMaxSize(); if (!$config->get('checkSizeAfterScaling') && $maxFileSize && $uploadedFile->getSize() > $maxFileSize) { throw new InvalidUploadException('Uploaded file is too big', Error::UPLOADED_TOO_BIG); } if (Image::isSupportedExtension($uploadedFile->getExtension())) { $imagesConfig = $config->get('images'); $image = Image::create($uploadedFile->getContents()); if ($image->getWidth() > $imagesConfig['maxWidth'] || $image->getHeight() > $imagesConfig['maxHeight']) { $image->resize($imagesConfig['maxWidth'], $imagesConfig['maxHeight'], $imagesConfig['quality']); $imageData = $image->getData(); $uploadedFile->setContents($imageData); } $cache->set(Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName), $image->getInfo()); unset($imageData); unset($image); } if ($maxFileSize && $uploadedFile->getSize() > $maxFileSize) { throw new InvalidUploadException('Uploaded file is too big', Error::UPLOADED_TOO_BIG); } $event = new FileUploadEvent($this->app, $uploadedFile); $dispatcher->dispatch(CKFinderEvent::FILE_UPLOAD, $event); if (!$event->isPropagationStopped()) { $uploadedFileStream = $uploadedFile->getContentsStream(); $uploaded = (int) $workingFolder->putStream($fileName, $uploadedFileStream); if ($overwriteOnUpload) { $thumbsRepository->deleteThumbnails($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName); } if (!$uploaded) { $warningErrorCode = Error::ACCESS_DENIED; } } $responseData = array('fileName' => $fileName, 'uploaded' => $uploaded); if ($warningErrorCode) { $errorMessage = $this->app['translator']->translateErrorMessage($warningErrorCode, array($fileName)); $responseData['error'] = array('number' => $warningErrorCode, 'message' => $errorMessage); } return $responseData; }
public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, Acl $acl, ResizedImageRepository $resizedImageRepository, ThumbnailRepository $thumbnailRepository, Config $config) { $fileName = (string) $request->get('fileName'); $newFileName = (string) $request->get('newFileName'); $editedImage = new EditedImage($fileName, $this->app, $newFileName); $resourceType = $workingFolder->getResourceType(); if (null === $newFileName) { $resourceTypeName = $resourceType->getName(); $path = $workingFolder->getClientCurrentFolder(); if (!$acl->isAllowed($resourceTypeName, $path, Permission::FILE_DELETE)) { throw new UnauthorizedException(sprintf('Unauthorized: no FILE_DELETE permission in %s:%s', $resourceTypeName, $path)); } } if (!Image::isSupportedExtension($editedImage->getExtension())) { throw new InvalidExtensionException('Unsupported image type or not image file'); } $image = Image::create($editedImage->getContents()); $actions = (array) $request->get('actions'); if (empty($actions)) { throw new InvalidRequestException(); } foreach ($actions as $actionInfo) { if (!isset($actionInfo['action'])) { throw new InvalidRequestException('ImageEdit: action name missing'); } switch ($actionInfo['action']) { case self::OPERATION_CROP: if (!Utils::arrayContainsKeys($actionInfo, array('x', 'y', 'width', 'height'))) { throw new InvalidRequestException(); } $x = $actionInfo['x']; $y = $actionInfo['y']; $width = $actionInfo['width']; $height = $actionInfo['height']; $image->crop($x, $y, $width, $height); break; case self::OPERATION_ROTATE: if (!isset($actionInfo['angle'])) { throw new InvalidRequestException(); } $degrees = $actionInfo['angle']; $bgcolor = isset($actionInfo['bgcolor']) ? $actionInfo['bgcolor'] : 0; $image->rotate($degrees, $bgcolor); break; case self::OPERATION_RESIZE: if (!Utils::arrayContainsKeys($actionInfo, array('width', 'height'))) { throw new InvalidRequestException(); } $imagesConfig = $config->get('images'); $width = $imagesConfig['maxWidth'] && $actionInfo['width'] > $imagesConfig['maxWidth'] ? $imagesConfig['maxWidth'] : $actionInfo['width']; $height = $imagesConfig['maxHeight'] && $actionInfo['height'] > $imagesConfig['maxHeight'] ? $imagesConfig['maxHeight'] : $actionInfo['height']; $image->resize((int) $width, (int) $height, $imagesConfig['quality']); break; } } $editFileEvent = new EditFileEvent($this->app, $editedImage); $editedImage->setNewContents($image->getData()); $editedImage->setNewDimensions($image->getWidth(), $image->getHeight()); if (!$editedImage->isValid()) { throw new InvalidUploadException('Invalid file provided'); } $dispatcher->dispatch(CKFinderEvent::EDIT_IMAGE, $editFileEvent); $saved = false; if (!$editFileEvent->isPropagationStopped()) { $saved = $editedImage->save($editFileEvent->getNewContents()); //Remove thumbnails and resized images in case if file is overwritten if ($newFileName === null && $saved) { $thumbnailRepository->deleteThumbnails($resourceType, $workingFolder->getClientCurrentFolder(), $fileName); $resizedImageRepository->deleteResizedImages($resourceType, $workingFolder->getClientCurrentFolder(), $fileName); } } return array('saved' => (int) $saved, 'date' => Utils::formatDate(time())); }
/** * Validates current file name * * @return bool true if file name is valid */ public function hasValidFilename() { return static::isValidName($this->fileName, $this->config->get('disallowUnsafeCharacters')); }