Make image and save to cache
@param string $filePath
@param array $params
@return string
162109
private function make($filePath, array $params)
    {
        if (!is_null($this->basePath)) {
            $fileFullPath = FileHelper::normalizePath(Yii::getAlias($this->basePath . '/' . $filePath));
        } else {
            $fileFullPath = FileHelper::normalizePath($filePath);
        }

        $fileFullPath = urldecode($fileFullPath);

        if (!is_file($fileFullPath)) {
            return false;
        }

        $quality = isset($params['quality']) ? $params['quality'] : $this->options['quality'];

        $cacheFileName = md5($fileFullPath . serialize($params) . $quality . filemtime($fileFullPath));
        $cacheFileExt = strrchr($fileFullPath, '.');
        $cacheFileDir = '/' . substr($cacheFileName, 0, 2);
        $cacheFilePath = Yii::getAlias($this->cachePath) . $cacheFileDir;
        $cacheFile = $cacheFilePath . '/' . $cacheFileName . $cacheFileExt;
        $cacheUrl = str_replace('\\', '/', preg_replace('/^@[a-z]+/', '', $this->cachePath) . $cacheFileDir . '/'
            . $cacheFileName . $cacheFileExt);

        $cacheUrl = !is_null($this->prefixPath) ? $this->prefixPath . $cacheUrl : $cacheUrl;

        if (file_exists($cacheFile)) {
            if ($this->cacheExpire !== 0 && (time() - filemtime($cacheFile)) > $this->cacheExpire) {
                unlink($cacheFile);
            } else {
                return $cacheUrl;
            }
        }

        if (!is_dir($cacheFilePath)) {
            mkdir($cacheFilePath, 0755, true);
        }

        try{
            $this->image = Image::getImagine()->open($fileFullPath);
        }catch(\Imagine\Exception\RuntimeException $e){
            return null;
        }catch(\Imagine\Exception\InvalidArgumentException $e){
            return null;
        }

        foreach ($params as $key => $value) {
            switch ($key) {
                case self::FUNCTION_THUMBNAIL :
                    $this->thumbnail($value);
                    break;
                case self::FUNCTION_RESIZE :
                    $this->resize($value);
                    break;
                case self::FUNCTION_CROP :
                    $this->crop($value);
                    break;
                case self::FUNCTION_WATERMARK :
                    $this->watermark($value);
                    break;
            }
        }

        $this->image->save($cacheFile, [
            'quality' => $quality
        ]);

        if (array_key_exists(self::FUNCTION_COMPRESS, $params)) {
            if ($params[self::FUNCTION_COMPRESS] && !is_null($this->options['tinyPng']['apiKey'])) {
                $result = $this->tiny->compress($cacheFile);
                $result->writeTo($cacheFile);
            }
        }

        return $cacheUrl;
    }
456484
public function getImageResponse($path, array $params)
    {
        if (is_null($this->responseFactory)) {
            throw new InvalidArgumentException(
                'Unable to get image response, no response factory defined.'
            );
        }

        $path = $this->makeImage($path, $params);

        return $this->responseFactory->create($this->cache, $path);
    }
472544
public function createFileOnDFS( $filePath, $contents )
    {
        $this->accumulatorStart();

        $filePath = $this->makeDFSPath( $filePath );
        $ret = $this->createFile( $filePath, $contents, false );

        $this->accumulatorStop();

        return $ret;
    }
807710
public function file($filePath, array $params = array())
    {
        if (!file_exists($filePath)) {
            throw new \Zend_Controller_Action_Exception(null, 404);
        }

        $this->disableViewAndLayout();
        $this->options = array_merge($this->options, $params);
        
        if (null === $this->options['size']) {
            $this->options['size'] = filesize($filePath);
        }
        
        if (null === $this->options['fileName']) {
            $this->options['fileName'] = pathinfo($filePath, PATHINFO_BASENAME);
        }

        if (null === $this->options['mimeType']) {
            $this->options['mimeType'] = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filePath);
        }

        $response = $this->getResponse();
        $response->clearAllHeaders();
        $response->clearBody();

        $response->setHeader(self::HEADER_MIME_TYPE, $this->options['mimeType']);
        $response->setHeader(self::HEADER_SIZE, $this->options['size']);
        
        if ($this->options['download']) {
            $response->setHeader(self::HEADER_DOWNLOAD, sprintf('attachment; filename="%s"', $this->options['fileName']));            
        }

        $this->buildHeaders($response, $this->options['headers']);
        
        $response->setBody(file_get_contents($filePath), $this->options['fileName']);
        $response->sendResponse();
        exit;
    }
361205
private function createSubfolder($path, array $params)
    {
        // Ensure the path ends in "/" and the body is empty.
        $params['Key'] = rtrim($params['Key'], '/') . '/';
        $params['Body'] = '';

        // Fail if this pseudo directory key already exists
        if ($this->getClient()->doesObjectExist(
            $params['Bucket'],
            $params['Key'])
        ) {
            return $this->triggerError("Subfolder already exists: {$path}");
        }

        return $this->boolCall(function () use ($params, $path) {
            $this->getClient()->putObject($params);
            $this->clearCacheKey($path);
            return true;
        });
    }
1276972
protected function getFileAsset($filePath)
    {
        $file = new \SplFileInfo($filePath);

        if (!$file->isReadable() || $file->isDir()) {
            return null;
        }

        $filePath = $file->getRealPath();

        return new FileAsset($filePath);
    }
889338
private function getMime($filePath)
    {
        $file = new File($filePath);
        $mime = $file->getMime();

        if (is_array($mime)) {
            $mime = reset($mime);
        }

        return $mime;
    }
1115557
public static function createFromFilePath ($filePath)
    {
        if (!is_file($filePath))
        {
            throw new \InvalidArgumentException("File does not exist");
        }
        else if (!is_readable($filePath))
        {
            throw new \InvalidArgumentException("File to download is not readable.");
        }

        return new FileDownload(fopen($filePath, "rb"));
    }
746571
protected function prepareUrls($filePath, array $urls = [], $forceRefresh = false, $cacheOnly = false, $shuffle = true)
    {
        $fileExists = file_exists($filePath);

        if ($cacheOnly) {
            if (!$fileExists) {
                $this->log->debug("Cache only mode enabled, but $filePath does not exist !");

                return [];
            }
            $this->log->debug("Cache only mode enabled, only loading content from $filePath");

            return [$filePath];
        } else {
            if ($shuffle) {
                shuffle($urls);
            }

            if ($forceRefresh) {
                $this->log->debug("Refresh forced, skipping cached content from $filePath");

                return $urls;
            }
            if ($fileExists) {
                array_unshift($urls, $filePath);
            }

            return $urls;
        }
    }
793085
public function get_thumbnail($filepath, $thumbsize) {
        global $CFG;

        $filepath = trim($filepath, '/');
        $origfile = $this->get_rootpath() . $filepath;
        // As thumbnail filename we use original file content hash.
        if (!$this->is_in_repository($filepath) || !($filecontents = @file_get_contents($origfile))) {
            // File is not found or is not readable.
            return null;
        }
        $filename = file_storage::hash_from_string($filecontents);

        // Try to get generated thumbnail for this file.
        $fs = get_file_storage();
        if (!($file = $fs->get_file(SYSCONTEXTID, 'repository_filesystem', $thumbsize, $this->id, '/' . $filepath . '/',
                $filename))) {
            // Thumbnail not found . Generate and store thumbnail.
            require_once($CFG->libdir . '/gdlib.php');
            if ($thumbsize === 'thumb') {
                $size = 90;
            } else {
                $size = 24;
            }
            if (!$data = generate_image_thumbnail_from_string($filecontents, $size, $size)) {
                // Generation failed.
                return null;
            }
            $record = array(
                'contextid' => SYSCONTEXTID,
                'component' => 'repository_filesystem',
                'filearea' => $thumbsize,
                'itemid' => $this->id,
                'filepath' => '/' . $filepath . '/',
                'filename' => $filename,
            );
            $file = $fs->create_file_from_string($record, $data);
        }
        return $file;
    }
793913
protected function compressFile($filepath)
	{
		if (!$this->getBackupFilesystemInstance()->checkFunctionExists('gzencode')) {
			throw new BackupException('The method: "gzencode" isn\'t currently enabled.');
		}

		$compressedFilepath = $this->getCompressedFilepath($filepath);
		$this->getBackupFilesystemInstance()->writeCompressedFile($compressedFilepath, $filepath);
		$this->getBackupFilesystemInstance()->removeFile($filepath);

		return $compressedFilepath;
	}
1295690
public function saveFile($filePath, $fileContent)
    {
        if (false === is_dir(dirname($filePath))) {
            mkdir(dirname($filePath), 0755);
        }

        return file_put_contents($filePath, $fileContent);
    }
426204
public function loadFile($filePath)
    {
        if (strrpos($filePath, $this->extension) !== false) {
            $fileKey = str_replace([$this->path, $this->extension, DIRECTORY_SEPARATOR], ['', '', '-'], $filePath);
            $this->store(camelcase($fileKey), new SplFileInfo($filePath));
        }
    }
436382
public static function createRequestUri($servicePath, $restPath, $params)
  {
    $requestUrl = $servicePath . $restPath;
    $uriTemplateVars = array();
    $queryVars = array();
    foreach ($params as $paramName => $paramSpec) {
      if ($paramSpec['type'] == 'boolean') {
        $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
      }
      if ($paramSpec['location'] == 'path') {
        $uriTemplateVars[$paramName] = $paramSpec['value'];
      } else if ($paramSpec['location'] == 'query') {
        if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
          foreach ($paramSpec['value'] as $value) {
            $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
          }
        } else {
          $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
        }
      }
    }

    if (count($uriTemplateVars)) {
      $uriTemplateParser = new URITemplate();
      $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
    }

    if (count($queryVars)) {
      $requestUrl .= '?' . implode($queryVars, '&');
    }

    return $requestUrl;
  }
1233712
public static function filename( $filePath, array $options = [])
    {
        extract( static::FilePathProperties($filePath) );

        $options = static::ExtendOptions($options);

        $stringOptions = static::BuildPathOptions($options);

        return sprintf( '%s/%s%s.%s', $dirname, $filename, $stringOptions, $extension );;
    }
51739
protected function createBackupFile($filePath)
    {
        $sourcePath = $filePath;
        $backupPath = $filePath.'.bak';

        if (file_exists($backupPath))
        {
            $date = new \DateTime();
            $backupPath = "{$filePath}{$date->getTimestamp()}.bak";
        }

        copy($sourcePath, $backupPath);
    }
5920
private function renderTemplate($filePath)
    {
        return $this->render(array(
            'url' => $this->url,
            'width' => $this->width,
            'height' => $this->height,
            'fullPage' => $this->fullPage,
            'timeout' => $this->timeout * 1000, // convert into milliseconds
            'waitForImages' => $this->waitForImages,
            'imagesLoadingTimeout' => $this->imagesLoadingTimeout * 1000, // convert into milliseconds
        ), $filePath);
    }