Beispiel #1
0
 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;
 }
Beispiel #2
0
 public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, CacheManager $cache, ResizedImageRepository $resizedImageRepository, ThumbnailRepository $thumbnailRepository, Acl $acl)
 {
     $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);
     }
     $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']));
 }
 /**
  * Main command method.
  *
  * @param Request       $request       Current request object
  * @param WorkingFolder $workingFolder Current working folder object
  *
  * @return array
  *
  * @throws \Exception
  */
 public function execute(Request $request, WorkingFolder $workingFolder)
 {
     $fileName = $request->get('fileName');
     $backend = $workingFolder->getBackend();
     if (!$workingFolder->containsFile($fileName)) {
         throw new \Exception('File not found', Error::FILE_NOT_FOUND);
     }
     $fileMetadada = $backend->getMetadata(Path::combine($workingFolder->getPath(), $fileName));
     return $fileMetadada;
 }
Beispiel #4
0
 /**
  * Deletes the current file.
  *
  * @return bool `true` if the file was deleted successfully.
  *
  * @throws \Exception
  */
 public function doDelete()
 {
     if ($this->resourceType->getBackend()->delete($this->getFilePath())) {
         $this->deleteThumbnails();
         $this->deleteResizedImages();
         $this->getCache()->delete(Path::combine($this->resourceType->getName(), $this->folder, $this->getFilename()));
         return true;
     } else {
         $this->addError(Error::ACCESS_DENIED);
         return false;
     }
 }
Beispiel #5
0
 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;
 }
 /**
  * Renames current file
  *
  * @return bool true if file was renamed successfully
  *
  * @throws \Exception
  */
 public function doRename()
 {
     $oldPath = Path::combine($this->getPath(), $this->getFilename());
     $newPath = Path::combine($this->getPath(), $this->newFileName);
     $backend = $this->resourceType->getBackend();
     if ($backend->has($newPath)) {
         throw new AlreadyExistsException('Target file already exists');
     }
     $this->deleteThumbnails();
     $this->resourceType->getResizedImageRepository()->renameResizedImages($this->resourceType, $this->folder, $this->getFilename(), $this->newFileName);
     $this->getCache()->move(Path::combine($this->resourceType->getName(), $this->folder, $this->getFilename()), Path::combine($this->resourceType->getName(), $this->folder, $this->newFileName));
     return $backend->rename($oldPath, $newPath);
 }
Beispiel #7
0
 /**
  * Moves the current file.
  *
  * @return bool `true` if the file was moved successfully.
  *
  * @throws \Exception
  */
 public function doMove()
 {
     $originalFilePath = $this->getFilePath();
     $originalFileName = $this->getFilename();
     // Save original file name - it may be autorenamed when copied
     if (parent::doCopy()) {
         // Remove source file
         $this->deleteThumbnails();
         $this->resourceType->getResizedImageRepository()->deleteResizedImages($this->resourceType, $this->folder, $originalFileName);
         $this->getCache()->delete(Path::combine($this->resourceType->getName(), $this->folder, $originalFileName));
         return $this->resourceType->getBackend()->delete($originalFilePath);
     }
     return false;
 }
 public function execute(WorkingFolder $workingFolder)
 {
     $directories = $workingFolder->listDirectories();
     $data = new \stdClass();
     $data->folders = array();
     $backend = $workingFolder->getBackend();
     $resourceType = $workingFolder->getResourceType();
     foreach ($directories as $directory) {
         $data->folders[] = array('name' => $directory['basename'], 'hasChildren' => $backend->containsDirectories($resourceType, Path::combine($workingFolder->getClientCurrentFolder(), $directory['basename'])), 'acl' => $directory['acl']);
     }
     // Sort folders
     usort($data->folders, function ($a, $b) {
         return strnatcasecmp($a['name'], $b['name']);
     });
     return $data;
 }
Beispiel #9
0
 public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher, CacheManager $cache, ResizedImageRepository $resizedImageRepository, ThumbnailRepository $thumbnailRepository)
 {
     $fileName = $request->query->get('fileName');
     $editedFile = new EditedFile($fileName, $this->app);
     $saveAsNew = false;
     if (!$editedFile->exists()) {
         $saveAsNew = true;
         $editedFile->saveAsNew(true);
     }
     if (!$editedFile->isValid()) {
         throw new InvalidUploadException('Invalid file provided');
     }
     if (!Image::isSupportedExtension($editedFile->getExtension())) {
         throw new InvalidExtensionException('Unsupported image type or not image file');
     }
     $imageFormat = Image::mimeTypeFromExtension($editedFile->getExtension());
     $uploadedData = $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();
     }
     $uploadedImage = Image::create($data);
     $newContents = $uploadedImage->getData($imageFormat);
     $editFileEvent = new EditFileEvent($this->app, $editedFile, $newContents);
     $cache->set(Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName), $uploadedImage->getInfo());
     $dispatcher->dispatch(CKFinderEvent::SAVE_IMAGE, $editFileEvent);
     $saved = false;
     if (!$editFileEvent->isPropagationStopped()) {
         $saved = $editedFile->setContents($editFileEvent->getNewContents());
         //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()));
 }
 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;
 }
 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));
 }
Beispiel #12
0
 /**
  * Destructor to remove temporary files if operation was started for current request
  */
 public function __destruct()
 {
     if ($this->startedOperationId) {
         $directoryPath = $this->getFilePath($this->startedOperationId, null);
         $toRemove = array($statusFilePath = Path::combine($directoryPath, 'status'), $abortFilePath = Path::combine($directoryPath, 'abort'));
         foreach ($toRemove as $filePath) {
             if (file_exists($filePath)) {
                 unlink($filePath);
             }
         }
         if (is_dir($directoryPath)) {
             rmdir($directoryPath);
         }
     }
 }
 /**
  * Returns backend-relative resized image file path
  *
  * @return string
  */
 public function getFilePath()
 {
     return Path::combine($this->getDirectory(), $this->getFileName());
 }
Beispiel #14
0
 /**
  * Checks if directory contains subdirectories
  *
  * @param Backend      $backend
  * @param ResourceType $resourceType
  * @param string       $clientPath
  * @param Acl          $acl
  *
  * @return bool
  */
 public function containsDirectories(Backend $backend, ResourceType $resourceType, $clientPath, Acl $acl)
 {
     $location = rtrim($this->applyPathPrefix(Path::combine($resourceType->getDirectory(), $clientPath)), '/\\') . '/';
     if (!is_dir($location) || false === ($fh = @opendir($location))) {
         return false;
     }
     $hasChildren = false;
     $resourceTypeName = $resourceType->getName();
     $clientPath = rtrim($clientPath, '/\\') . '/';
     while (false !== ($filename = readdir($fh))) {
         if ($filename == '.' || $filename == '..') {
             continue;
         }
         if (is_dir($location . $filename)) {
             if (!$acl->isAllowed($resourceTypeName, $clientPath . $filename, Permission::FOLDER_VIEW)) {
                 continue;
             }
             if ($backend->isHiddenFolder($filename)) {
                 continue;
             }
             $hasChildren = true;
             break;
         }
     }
     closedir($fh);
     return $hasChildren;
 }
 /**
  * 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;
 }
Beispiel #16
0
 /**
  * Disallows a permission for a given role.
  *
  * @param string $resourceType
  * @param string $folderPath
  * @param int    $permission
  * @param string $role
  *
  * @return $this|Acl
  */
 public function disallow($resourceType, $folderPath, $permission, $role)
 {
     $folderPath = Path::normalize($folderPath);
     if (!isset($this->rules[$folderPath][$role][$resourceType])) {
         $this->rules[$folderPath][$role][$resourceType] = new MaskBuilder();
     }
     /* @var $ruleMask MaskBuilder */
     $ruleMask = $this->rules[$folderPath][$role][$resourceType];
     $ruleMask->disallow($permission);
     return $this;
 }
 /**
  * Deletes all thumbnails under the given path defined by the resource type,
  * path and file name.
  *
  * @param ResourceType $resourceType
  * @param string       $path
  * @param string       $fileName
  *
  * @return bool `true` if deleted successfully
  */
 public function deleteThumbnails(ResourceType $resourceType, $path, $fileName = null)
 {
     $path = Path::combine($this->getThumbnailsPath(), $resourceType->getName(), $path, $fileName);
     if ($this->thumbsBackend->has($path)) {
         return $this->thumbsBackend->deleteDir($path);
     }
     return false;
 }
Beispiel #18
0
 /**
  * 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;
 }
Beispiel #19
0
 /**
  * Returns a direct url to a file
  *
  * @param string $path
  *
  * @return string|null direct url to a file or null if backend
  *                     doesn't support direct access
  */
 public function getFileUrl($path)
 {
     if (method_exists($this->adapter, 'getFileUrl')) {
         return $this->adapter->getFileUrl($path);
     }
     if (isset($this->backendConfig['baseUrl'])) {
         return Path::combine($this->backendConfig['baseUrl'], Utils::encodeURLParts($path));
     }
     return null;
 }
Beispiel #20
0
 public function setContents($contents, $filePath = null)
 {
     return parent::setContents($contents, $this->newFileName ? Path::combine($this->getPath(), $this->newFileName) : null);
 }
Beispiel #21
0
 /**
  * Registers stream handler for errors logging
  */
 public function registerStreamLogger()
 {
     $app = $this;
     /* @var $logsBackend \CKSource\CKFinder\Backend\Backend */
     $logsBackend = $app['backend_factory']->getPrivateDirBackend('logs');
     $adapter = $logsBackend->getAdapter();
     if ($adapter instanceof LocalFSAdapter) {
         $logsDir = $app['config']->getPrivateDirPath('logs');
         $errorLogPath = Path::combine($logsDir, 'error.log');
         $logPath = $adapter->applyPathPrefix($errorLogPath);
         $app['logger']->pushHandler(new StreamHandler($logPath));
     }
 }
Beispiel #22
0
 /**
  * Creates a resized image.
  */
 public function create()
 {
     if (null === $this->image) {
         $sourceFilePath = Path::combine($this->sourceFileResourceType->getDirectory(), $this->sourceFileDir, $this->sourceFileName);
         if ($this->backend->isHiddenFile($this->sourceFileName) || !$this->backend->has($sourceFilePath)) {
             throw new FileNotFoundException('ResizedImage::create(): Source file not found');
         }
         $this->image = Image::create($this->backend->read($sourceFilePath));
     }
     $this->image->resize($this->width, $this->height);
     $this->resizedImageData = $this->image->getData();
     $this->resizedImageSize = $this->image->getDataSize();
     $this->resizedImageMimeType = $this->image->getMimeType();
 }
Beispiel #23
0
 /**
  * Checks if the current file folder path is valid.
  *
  * @return bool `true` if the path is valid.
  */
 public function hasValidPath()
 {
     return Path::isValid($this->getPath());
 }
Beispiel #24
0
 /**
  * Renames current file by adding number to file name.
  *
  * Renaming is done by adding number in parenthesis until file name doesn't
  * collide with any other file existing in target backend/path.
  * For example, if target backend path contains file named foo.txt
  * and current file name is foo.txt, this method will change current file
  * name to foo(1).txt.
  *
  * @param Backend $backend target backend
  * @param string  $path    target backend relative path
  *
  * @return bool true if file was renamed
  */
 public function autorename(Backend $backend = null, $path = '')
 {
     $filePath = Path::combine($path, $this->fileName);
     if (!$backend->has($filePath)) {
         return false;
     }
     $pieces = explode('.', $this->fileName);
     $basename = array_shift($pieces);
     $extension = implode('.', $pieces);
     $i = 0;
     while (true) {
         $i++;
         $this->fileName = "{$basename}({$i}).{$extension}";
         $filePath = Path::combine($path, $this->fileName);
         if (!$backend->has($filePath)) {
             break;
         }
     }
     return true;
 }
Beispiel #25
0
 /**
  * @param ResourceType $resourceType resource type
  * @param string       $path         resource type relative path
  */
 public function __construct(ResourceType $resourceType, $path)
 {
     $this->resourceType = $resourceType;
     $this->path = Path::combine($resourceType->getDirectory(), $path);
 }
Beispiel #26
0
 /**
  * Adds current folder info to the response
  *
  * @param FilterResponseEvent $event
  */
 public function addCurrentFolderInfo(FilterResponseEvent $event)
 {
     /* @var JsonResponse $response */
     $response = $event->getResponse();
     if ($response instanceof JsonResponse) {
         $responseData = (array) $response->getData();
         $responseData = array('resourceType' => $this->getResourceTypeName(), 'currentFolder' => array('path' => $this->getClientCurrentFolder(), 'acl' => $this->getAclMask())) + $responseData;
         $baseUrl = $this->backend->getBaseUrl();
         if (null !== $baseUrl) {
             $folderUrl = Path::combine($baseUrl, Utils::encodeURLParts(Path::combine($this->resourceType->getDirectory(), $this->getClientCurrentFolder())));
             $responseData['currentFolder']['url'] = rtrim($folderUrl, '/') . '/';
         }
         $response->setData($responseData);
     }
 }
Beispiel #27
0
 /**
  * Returns source file name of the copied file
  *
  * @return string
  */
 public function getSourceFilePath()
 {
     return Path::combine($this->getPath(), $this->sourceFileName);
 }
 /**
  * @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;
 }
Beispiel #29
0
 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;
 }
Beispiel #30
0
 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;
 }