Get the stored path for a file.

@param int $file_id
@param int $version_id
@param int $storage_location_id
@param string $thumbnail_handle
@param string $format

@return null|string
165451
protected function getStoredThumbnailPath($file_id, $version_id, $storage_location_id, $thumbnail_handle, $format)
    {
        $builder = $this->connection->createQueryBuilder();
        $query = $builder
            ->select('path')->from('FileImageThumbnailPaths', 'p')
            ->where('p.fileID = :file')
            ->andWhere('p.fileVersionID = :version')
            ->andWhere('p.storageLocationID = :storage')
            ->andWhere('p.thumbnailTypeHandle = :thumbnail')
            ->andWhere('p.thumbnailFormat = :format')
            ->setParameters(array(
                'file' => $file_id,
                'version' => $version_id,
                'storage' => $storage_location_id,
                'thumbnail' => $thumbnail_handle,
                'format' => $format,
            ))->execute();

        if ($query->rowCount()) {
            return $query->fetchColumn();
        }

        return null;
    }
205215
def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False):
    
    profile, base_name = img_id.split(':', 1)
    conf = get_profile_configs(profile)
    if not variant_label:
        status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX
    else:
        status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX
    name, file_ext = os.path.splitext(base_name)
    prefix = ''
    if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):
        name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):]
        prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX
    name_parts = name.split('_', 2)
    name = '{name}{status_suffix}{hash}'.format(
        name=name,
        status_suffix=status_suffix,
        hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label)
    )
    if variant_label:
        name += '_' + variant_label
    if ext:
        file_ext = ext
    elif variant_label:
        for var_conf in conf['VARIANTS']:
            var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf)
            if var_conf_label == variant_label:
                if var_conf['FORMAT']:
                    file_ext = var_conf['FORMAT'].lower()
                break
    if file_ext and not file_ext.startswith('.'):
        file_ext = '.' + file_ext
    relative_path = os.path.join(
        dju_settings.DJU_IMG_UPLOAD_SUBDIR,
        conf['PATH'],
        name_parts[0][-2:],
        (prefix + name + file_ext)
    ).replace('\\', '/')
    if create_dirs:
        path = media_path(relative_path)
        make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR)
    return relative_path
1041884
public function viewImageAction(Request $request, $id, $format = MediaProviderInterface::FORMAT_REFERENCE)
    {
        $media = $this->getMedia($id);

        if (!$media) {
            throw new NotFoundHttpException(sprintf('unable to find the media with the id : %s', $id));
        }

        if (!$this->get('sonata.media.pool')->getDownloadStrategy($media)->isGranted($media, $request)) {
            throw new AccessDeniedException();
        }
        $provider = $this->getProvider($media);

        return new RedirectResponse($provider->generatePublicUrl($media, $format));
    }
114213
public static function getByPath($path, $version = 'RECENT')
    {
        $path = rtrim($path, '/'); // if the path ends in a / remove it.

        $cID = CacheLocal::getEntry('page_id_from_path', $path);
        if ($cID == false) {
            $db = Database::connection();
            $cID = $db->fetchColumn('select cID from PagePaths where cPath = ?', array($path));
            CacheLocal::set('page_id_from_path', $path, $cID);
        }

        return static::getByID($cID, $version);
    }
178021
protected function getFilepath($id, $pathPrefix = null)
	{
		if ($pathPrefix === null)
		{
			$pathPrefix = $this->uploadPath;
		}
		else
		{
			$pathPrefix = rtrim($pathPrefix, $this->pathTrimMask);
		}

		return $pathPrefix . '/' . $id;
	}
1257211
public function readFile($path, $file_handle = NULL) {/*{{{*/
        return $this->_do_request('GET', $path, NULL, NULL, $file_handle);
    }
395597
private function processFile($upload_path, $filename, $data, $id = null, $preserveFilePath = false) {
		if(!file_exists($upload_path.'/'.$filename)) {
            Logger::error("\tFile $filename is missing.");
			return $data;
		}

		if(isset($data['s3'])) {
			$key = $data['s3']['key'];

			if($key == $filename) {
				return $data;
			}

			$this->deleteFile($key);
		}

		$shouldUseCustomPrefix = (!empty(StorageSettings::prefixFormat()) && apply_filters('ilab_storage_should_use_custom_prefix', true));

		if (!$preserveFilePath && !isset($data['prefix']) && !$shouldUseCustomPrefix) {
		    $fpath = pathinfo($data['file'],PATHINFO_DIRNAME);
		    $fpath = str_replace($upload_path, '', $fpath);
		    $prefix = trailingslashit(ltrim($fpath, DIRECTORY_SEPARATOR));
            if ($prefix == './') {
                $prefix = trailingslashit(pathinfo($filename, PATHINFO_DIRNAME));
            }
        } else {
            $prefix = ($preserveFilePath && isset($data['prefix'])) ? $data['prefix'].DIRECTORY_SEPARATOR : StorageSettings::prefix($id);
        }

        $parts = explode('/', $filename);
        $bucketFilename = array_pop($parts);

		try {
            Logger::info("\tUploading $filename to S3.");
            $url = $this->client->upload($prefix.$bucketFilename, $upload_path.'/'.$filename, StorageSettings::privacy(), StorageSettings::cacheControl(), StorageSettings::expires());
            Logger::info("\tFinished uploading $filename to S3.");

			$options = [];
			$params = [];
			if(!empty(StorageSettings::cacheControl())) {
				$params['CacheControl'] = StorageSettings::cacheControl();
			}

			if(!empty(StorageSettings::expires())) {
				$params['Expires'] = StorageSettings::expires();
			}

			if(!empty($params)) {
				$options['params'] = $params;
			}

			$providerClass = get_class($this->client);
			$providerId = $providerClass::identifier();

			$data['s3'] = [
				'url' => $url,
				'bucket' => $this->client->bucket(),
				'privacy' => StorageSettings::privacy(),
				'key' => $prefix.$bucketFilename,
                'provider' =>  $providerId,
				'options' => $options
			];

			if(file_exists($upload_path.'/'.$filename)) {
				$ftype = wp_check_filetype($upload_path.'/'.$filename);
				if(!empty($ftype) && isset($ftype['type'])) {
					$data['s3']['mime-type'] = $ftype['type'];
				}
			}
		}
		catch(StorageException $ex) {
			Logger::error('Upload Error', [
				'exception' => $ex->getMessage(),
				'prefix' => $prefix,
				'bucketFilename' => $bucketFilename,
				'privacy' => StorageSettings::privacy()
			]);
		}

		if(StorageSettings::deleteOnUpload()) {
			if(file_exists($upload_path.'/'.$filename)) {
				unlink($upload_path.'/'.$filename);
			}
		}

		return $data;
	}
53862
public function getMethod($routeId, $version, $method)
    {
        if ($version == '*' || empty($version)) {
            $version = $this->methodTable->getLatestVersion($routeId);
        } else {
            $version = $this->methodTable->getVersion($routeId, $version);
        }

        if (empty($version)) {
            throw new StatusCode\UnsupportedMediaTypeException('Version does not exist');
        }

        return $this->methodTable->getMethod($routeId, $version, $method);
    }
1346824
protected function getPathUrl($prePath, $id, $fileName, $format, $version = '', $subVersion = '')
    {
        $segment = $this->getSegment($id) . '/';
        $prePath = rtrim($prePath, '/');

        return str_replace(
            '{slug}',
            $format . '/' . $segment . $id . '-' . rawurlencode($fileName),
            $prePath
        ) . '?v=' . $version . '-' . $subVersion;
    }
1301721
protected function getAvatarUrl( $id, $size ) {
		$attachments_fallback_chain = $this->getAttachmentFallbackChain( $id );

		foreach ( $attachments_fallback_chain as $attachment_id ) {
			$image = wp_get_attachment_image_src( $attachment_id, $size );
			if ( ! empty( $image ) ) {
				return $image[0];
			}
		}

		return null;
	}
1039037
protected function getUri($name, $format = null) {
		$path = param('static.path.' . $this->pathName) . '/';
		$fileName = $path . $this->getFileName($name, $format);
		return $fileName;
	}
279223
public function fileAction($storageId)
    {
        $fileManager = $this->get('beaast.core.manager.file');

        /**
         * @var File $file
         */
        $file = $fileManager->findOneBy(['storageId' => $storageId]);

        if (!$file) {
            return new Response('File not found.', 404);
        }

        $filePath = $fileManager->getFilePath($file);

        $headers = array();
        if ($file->getExtension() === 'png') {
            $headers = array(
                'Content-Type'     => 'image/png',
                'Content-Disposition' => 'inline; filename="'.$file->getFileName().'"',
            );
        } elseif ($file->getExtension() === 'jpg') {
            $headers = array(
                'Content-Type'     => 'image/jpg',
                'Content-Disposition' => 'inline; filename="'.$file->getFileName().'"',
            );
        } elseif ($file->getExtension() === 'pdf' || $file->getExtension() === 'xlsx') {
            $headers = array(
                'Cache-Control'     => 'private',
                'Content-Type'     => $file->getMimeType(),
                'Content-length'     => $file->getSize(),
                'Content-Disposition' => 'attachment; filename="'.$file->getFileName().'"',
            );
        }

        return new Response(file_get_contents($filePath), 200, $headers);
    }
593530
private function getPath(string $id, string $key) : string
    {
        // Sanitize the session key: it may contain characters that could conflict with the filesystem.
        // We only allow the resulting file name to contain ASCII letters & digits, dashes, underscores and dots.
        // All other chars are hex-encoded, dot is used as an escape character.
        $key = preg_replace_callback('/[^A-Za-z0-9\-_]/', static function ($matches) {
            return '.' . bin2hex($matches[0]);
        }, $key);

        return $this->directory . DIRECTORY_SEPARATOR . $this->prefix . $id . '_' . $key;
    }
146071
protected function getPreviewsFromFileVersion($mediaId, $fileVersion, $locale)
    {
        $title = '';
        /*
         * @var FileVersionMeta
         */
        foreach ($fileVersion->getMeta() as $key => $meta) {
            if ($meta->getLocale() == $locale) {
                $title = $meta->getTitle();
                break;
            } elseif (0 == $key) { // fallback title
                $title = $meta->getTitle();
            }
        }

        $mediaFormats = $this->formatManager->getFormats(
            $mediaId,
            $fileVersion->getName(),
            $fileVersion->getStorageOptions(),
            $fileVersion->getVersion(),
            $fileVersion->getSubVersion(),
            $fileVersion->getMimeType()
        );

        foreach ($mediaFormats as $formatName => $formatUrl) {
            if ($formatName == $this->collectionPreviewFormat) {
                return [
                    'url' => $formatUrl,
                    'title' => $title,
                ];
                break;
            }
        }

        return [];
    }
719582
public function getFileReferenceData($fieldId, $versionNo)
    {
        $connection = $this->getConnection();

        $selectQuery = $connection->createSelectQuery();

        $this->setFetchColumns($selectQuery, $fieldId, $versionNo);

        $selectQuery->from(
            $connection->quoteTable($this->getStorageTable())
        )->where(
            $selectQuery->expr->lAnd(
                $selectQuery->expr->eq(
                    $connection->quoteColumn('contentobject_attribute_id'),
                    $selectQuery->bindValue($fieldId, null, \PDO::PARAM_INT)
                ),
                $selectQuery->expr->eq(
                    $connection->quoteColumn('version'),
                    $selectQuery->bindValue($versionNo, null, \PDO::PARAM_INT)
                )
            )
        );

        $statement = $selectQuery->prepare();
        $statement->execute();

        $result = $statement->fetchAll(\PDO::FETCH_ASSOC);

        if (count($result) < 1) {
            return null;
        }

        $convertedResult = array();
        foreach (reset($result) as $column => $value) {
            $convertedResult[$this->toPropertyName($column)] = $this->castToPropertyValue($value, $column);
        }
        $convertedResult['id'] = $this->prependMimeToPath(
            $convertedResult['id'],
            $convertedResult['mimeType']
        );

        return $convertedResult;
    }
586112
public function viewAction($id, $format = MediaProviderInterface::FORMAT_REFERENCE)
    {
        $media = $this->getMedia($id);

        if (!$media) {
            throw new NotFoundHttpException(sprintf('unable to find the media with the id : %s', $id));
        }

        if (!$this->get('sonata.media.pool')->getDownloadSecurity($media)->isGranted($media, $this->getCurrentRequest())) {
            throw new AccessDeniedException();
        }

        return $this->render('@SonataMedia/Media/view.html.twig', [
            'media' => $media,
            'formats' => $this->get('sonata.media.pool')->getFormatNamesByContext($media->getContext()),
            'format' => $format,
        ]);
    }
1172311
def get_thumb(self, path, key, format):
        
        thumbpath = self.get_thumbpath(path, key, format)
        fullpath = os.path.join(self.out_path, thumbpath)
        if os.path.isfile(fullpath):
            url = self.get_url(thumbpath)
            return Thumb(url, key)
        return Thumb()