Prepares an image for cropping and returns payload containing a URL
@param string $path
@param string $cropSessionKey
@param array $params
@return array
196536
protected function getCropEditImageUrlAndSize($path, $cropSessionKey, $params = null)
    {
        $sessionDirectoryPath = $this->getCropSessionDirPath($cropSessionKey);
        $fullSessionDirectoryPath = temp_path($sessionDirectoryPath);
        $sessionDirectoryCreated = false;

        if (!File::isDirectory($fullSessionDirectoryPath)) {
            File::makeDirectory($fullSessionDirectoryPath, 0777, true, true);
            $sessionDirectoryCreated = true;
        }

        $tempFilePath = null;

        try {
            $extension = pathinfo($path, PATHINFO_EXTENSION);
            $library = MediaLibrary::instance();
            $originalThumbFileName = 'original.'.$extension;

            /*
             * If the target dimensions are not provided, save the original image to the
             * crop session directory and return its URL.
             */
            if (!$params) {
                $tempFilePath = $fullSessionDirectoryPath.'/'.$originalThumbFileName;

                if (!@File::put($tempFilePath, $library->get($path))) {
                    throw new SystemException('Error saving remote file to a temporary location.');
                }

                $url = $this->getThumbnailImageUrl($sessionDirectoryPath.'/'.$originalThumbFileName);
                $dimensions = getimagesize($tempFilePath);

                return [
                    'url' => $url,
                    'dimensions' => $dimensions
                ];
            }
            /*
             * If the target dimensions are provided, resize the original image and
             * return its URL and dimensions.
             */

            $originalFilePath = $fullSessionDirectoryPath.'/'.$originalThumbFileName;
            if (!File::isFile($originalFilePath)) {
                throw new SystemException('The original image is not found in the cropping session directory.');
            }

            $resizedThumbFileName = 'resized-'.$params['width'].'-'.$params['height'].'.'.$extension;
            $tempFilePath = $fullSessionDirectoryPath.'/'.$resizedThumbFileName;

            Resizer::open($originalFilePath)
                ->resize($params['width'], $params['height'], [
                    'mode' => 'exact'
                ])
                ->save($tempFilePath)
            ;

            $url = $this->getThumbnailImageUrl($sessionDirectoryPath.'/'.$resizedThumbFileName);
            $dimensions = getimagesize($tempFilePath);

            return [
                'url' => $url,
                'dimensions' => $dimensions
            ];
        }
        catch (Exception $ex) {
            if ($sessionDirectoryCreated) {
                @File::deleteDirectory($fullSessionDirectoryPath);
            }

            if ($tempFilePath) {
                File::delete($tempFilePath);
            }

            throw $ex;
        }
    }
753646
public function readSrc($path) {
        $disk = $this->getSrcDisk();
        if ($disk->has($path)) return $disk->read($path);
        else throw new NotFoundHttpException('Croppa: Src image is missing');
    }
456660
static public function buildUrl($path, $params=null)
	{
	    $parts = explode('?', $path, 2);
	    $pathParams = isset($parts[1]) ? static::parseQuery($parts[1]) : [];
	    if (is_string($params)) {
	        $params = static::parseQuery($params);
	    }
	    if ($params) {
	        $pathParams = array_merge($pathParams, $params);
	    }
	    
	    return $parts[0] . ($pathParams ? '?' . http_build_query($pathParams) : '');
	}
951724
public function fields($fields, $path = null)
    {
        if (is_null($fields)) return;

        $path = $path ?: __DIR__.'/../tmp-fields.txt';
        $fields = preg_split('/, ?/', $fields);
        $arrayFields = array();

        foreach($fields as $pair)
        {
            list($key, $val) = preg_split('/ ?: ?/', $pair);
            $arrayFields[$key] = $val;
        }

        return $this->file->put($path, json_encode($arrayFields));
    }
13051
public function onCropImage()
    {
        $this->abortIfReadOnly();

        $imageSrcPath = trim(Input::get('img'));
        $selectionData = Input::get('selection');
        $cropSessionKey = Input::get('cropSessionKey');
        $path = Input::get('path');
        $path = MediaLibrary::validatePath($path);

        if (!strlen($imageSrcPath)) {
            throw new ApplicationException('Invalid input data');
        }

        if (!preg_match('/^[0-9a-z]+$/', $cropSessionKey)) {
            throw new ApplicationException('Invalid input data');
        }

        if (!is_array($selectionData)) {
            throw new ApplicationException('Invalid input data');
        }

        $result = $this->cropImage($imageSrcPath, $selectionData, $cropSessionKey, $path);

        $selectionMode = Input::get('selectionMode');
        $selectionWidth = Input::get('selectionWidth');
        $selectionHeight = Input::get('selectionHeight');

        $this->setSelectionParams($selectionMode, $selectionWidth, $selectionHeight);

        return $result;
    }
169702
public function put($path, $params)
    {
        $response = $this->http_client->request('PUT', $path, $params);
        $this->handleErrors($response);
        return $response;
    }
406872
public function crop($inputPDFPath, $outputPDFPath, $padding = 10, $x2 = null, $y1 = null, $y2 = null)
    {
        $inputDoc = new \PDFDoc($inputPDFPath);
        $inputDoc->InitSecurityHandler();

        $iterator = $inputDoc->GetPageIterator();
        for ($iterator; $iterator->HasNext(); $iterator->Next()) {
            $mediaBox = new \Rect($iterator->Current()->GetMediaBox());

            $mediaBox->x1 += $padding;
            $mediaBox->x2 -= empty($x2) ? $padding : $x2;
            $mediaBox->y1 += empty($y1) ? $padding : $y1;
            $mediaBox->y2 -= empty($y2) ? $padding : $y2;

            $mediaBox->Update();
        }

        $inputDoc->Save($outputPDFPath, 0);
        $inputDoc->Close();
    }
163253
public function request($path, array $parameters = array(), $httpMethod = 'GET', array $headers = array())
    {
        $client = $this->getHttpClient($path);
        $request = $client->getRequest();
        $client->setMethod($httpMethod);
        $client->setHeaders($headers);

        if ($httpMethod == 'GET') {
            $query = $request->getQuery();
            foreach ($parameters as $key => $value) {
                $query->set($key, $value);
            }
        } elseif ($httpMethod == 'POST') {
            $request->setContent(json_encode($parameters));
        }

        //Trigger Pre Send Event to modify Request Object
        $this->getEventManager()->trigger('pre.send', $request);

        $response = $client->dispatch($request);
        $this->response = $response;

        //Trigger Post Send to Modify/Validate Response object
        $result = $this->getEventManager()->trigger('post.send', $response);
        if ($result->stopped()) {
            $response = $result->last();
        }

        $this->request = $request;

        return $response;
    }
104306
public function render($request_path) {

        // Get crop path relative to it's dir
        $crop_path = $this->url->relativePath($request_path);

        // If the crops_dir is a remote disk and if the crop has already been
        // created.  If it has, just return that path.
        if ($this->storage->cropsAreRemote()
            && $this->storage->cropExists($crop_path)) {
            return $crop_path;
        }

        // Parse the path.  In the case there is an error (the pattern on the route
        // SHOULD have caught all errors with the pattern) just return
        if (!$params = $this->url->parse($request_path)) return;
        list($path, $width, $height, $options) = $params;

        // Check if there are too many crops already
        if ($this->storage->tooManyCrops($path)) throw new Exception('Croppa: Max crops');

        // Increase memory limit, cause some images require a lot to resize
        if ($this->config['memory_limit'] !== null) {
            ini_set('memory_limit', $this->config['memory_limit']);
        }

        // Build a new image using fetched image data
        $image = new Image(
            $this->storage->readSrc($path),
            $this->url->phpThumbConfig($options)
        );

        // Process the image and write its data to disk
        $this->storage->writeCrop($crop_path,
            $image->process($width, $height, $options)->get()
        );

        // Return the paht to the crop, relative to the storage disk
        return $crop_path;
    }
116161
protected function httpGet(string $path, array $params = [], array $requestHeaders = []): ResponseInterface
    {
        if (count($params) > 0) {
            $path .= '?'.http_build_query($params);
        }

        return $this->httpClient->sendRequest(
            $this->requestBuilder->create('GET', $path, $requestHeaders)
        );
    }
1074474
protected function prepareToDestroy(array $params = [], array $paramsFromSession = null)
    {
        $return = [];
        foreach ($paramsFromSession as $name => $values) {
            if ($params['column'] == $name) {
                $return[$name] = [];
            }
//            if (!empty($values['values'])) {
//                $return[$name]['values'] = $values['values'];
//            }
//            if (!isset($return[$name]['classname'])) {
//                $return[$name]['classname'] = $paramsFromSession[$name]['classname'];
//            }
        }
        return $return;
    }
1061469
public function convertAvatar($projectId, $cropperWidth, $cropperOffsetX, $cropperOffsetY, $needsCropping)
    {
        return $this->apiClient->callEndpoint(
            sprintf('%s/%s/avatar', self::ENDPOINT, $projectId),
            array(
                "cropperWidth" => $cropperWidth,
                "cropperOffsetX" => $cropperOffsetX,
                "cropperOffsetY" => $cropperOffsetY,
                "needsCropping" => $needsCropping
            ),
            HttpMethod::REQUEST_POST
        );
    }
78969
public function makeImage($path, array $params)
    {
        $sourcePath = $this->getSourcePath($path);
        $cachedPath = $this->getCachePath($path, $params);

        if ($this->cacheFileExists($path, $params) === true) {
            return $cachedPath;
        }

        if ($this->sourceFileExists($path) === false) {
            throw new FileNotFoundException(
                'Could not find the image `'.$sourcePath.'`.'
            );
        }

        $source = $this->source->read(
            $sourcePath
        );

        if ($source === false) {
            throw new FilesystemException(
                'Could not read the image `'.$sourcePath.'`.'
            );
        }

        // We need to write the image to the local disk before
        // doing any manipulations. This is because EXIF data
        // can only be read from an actual file.
        $tmp = tempnam(sys_get_temp_dir(), 'Glide');

        if (file_put_contents($tmp, $source) === false) {
            throw new FilesystemException(
                'Unable to write temp file for `'.$sourcePath.'`.'
            );
        }

        try {
            $write = $this->cache->write(
                $cachedPath,
                $this->api->run($tmp, $this->getAllParams($params))
            );

            if ($write === false) {
                throw new FilesystemException(
                    'Could not write the image `'.$cachedPath.'`.'
                );
            }
        } catch (FileExistsException $exception) {
            // This edge case occurs when the target already exists
            // because it's currently be written to disk in another
            // request. It's best to just fail silently.
        } finally {
            unlink($tmp);
        }

        return $cachedPath;
    }
1216177
protected function request($path, $params = [], $type = 'GET')
    {
        $path = 'sms/' . $path;

        // default params
        if (empty($this->config[ 'serverIp' ])) {
            throw new \InvalidArgumentException('RajaSMS: Server Ip Address is not set!');
        }

        if (empty($this->config[ 'apiKey' ])) {
            throw new \InvalidArgumentException('RajaSMS: API Key is not set');
        } else {
            $params[ 'apikey' ] = $this->config[ 'apiKey' ];
        }

        if ( ! empty($this->config[ 'callbackUrl' ]) and isset($params[ 'datapacket' ])) {
            $params[ 'callbackurl' ] = $this->config[ 'callbackUrl' ];
        }

        $uri = (new Uri($this->config[ 'serverIp' ]))->withPath($path);

        $request = new Curl\Request();

        $request->setConnectionTimeout(500);

        switch ($type) {
            default:
            case 'GET':
                $this->response = $request->setUri($uri)->get($params);
                break;

            case 'POST':
                $request->addHeader('content-type', 'application/json');
                $this->response = $request->setUri($uri)->post($params, 'JSON');
                break;
        }

        if (false !== ($error = $this->response->getError())) {
            $this->addError($error->code, $error->message);
        } elseif ($body = $this->response->getBody()) {
            return $body;
        }

        return false;
    }
167047
public function url($path, array $params = [])
    {
        $urlBuilder = UrlBuilderFactory::create($this->config['base_url'], $this->config['sign_key']);

        return $urlBuilder->getUrl($path, $params);
    }
604390
public function generateSignature($path, array $params)
    {
        unset($params['s']);
        ksort($params);

        return md5($this->signKey.':'.ltrim($path, '/').'?'.http_build_query($params));
    }
10161
protected function put(string $path, array $params = [], array $headers = [])
    {
        $body = self::createJsonBody($params);

        if ($body) {
            $headers = self::addJsonContentType($headers);
        }

        return $this->putRaw($path, $body, $headers);
    }