From 1641a9229dc4481791ce70720078ac0de7a3af11 Mon Sep 17 00:00:00 2001 From: maztch Date: Thu, 24 Feb 2022 10:21:29 +0100 Subject: [PATCH] upgrade php --- .travis.yml | 2 +- changelog.md | 20 ++ circle.yml | 2 +- composer.json | 15 +- init.php | 42 --- phpunit.no_autoload.xml | 15 - psalm.xml | 15 + readme.md | 13 +- src/Element.php | 2 +- src/Exceptions/ExtendedException.php | 16 +- src/Http/Client.php | 43 +++ src/Http/ClientException.php | 7 + src/Ilovepdf.php | 144 ++++---- src/Lib/JWT.php | 366 ------------------- src/Request/Body.php | 66 ---- src/Request/Method.php | 75 ---- src/Request/Request.php | 517 --------------------------- src/Request/Response.php | 78 ---- src/Task.php | 178 +++++---- src/WatermarkTask.php | 6 +- tests/bootstrap.no_autoload.php | 3 - 21 files changed, 291 insertions(+), 1334 deletions(-) delete mode 100755 init.php delete mode 100644 phpunit.no_autoload.xml create mode 100644 psalm.xml create mode 100644 src/Http/Client.php create mode 100644 src/Http/ClientException.php delete mode 100644 src/Lib/JWT.php delete mode 100644 src/Request/Body.php delete mode 100644 src/Request/Method.php delete mode 100644 src/Request/Request.php delete mode 100644 src/Request/Response.php delete mode 100755 tests/bootstrap.no_autoload.php diff --git a/.travis.yml b/.travis.yml index 84f0d05..ec92f46 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,9 @@ language: php php: - - '7.3' - '7.4' - '8.0' + - '8.1' before_script: composer install \ No newline at end of file diff --git a/changelog.md b/changelog.md index 7bd382a..ad62756 100644 --- a/changelog.md +++ b/changelog.md @@ -1,6 +1,26 @@ Changelog --------- + +v1.2.2 + +* Compatibility with php 8.1 +* Upgraded php version requirements +* Only composer use mode +* Code cleaned +* Improved exception messages + +v1.2.1 + +* New tool editpdf added + +v1.1.18 + +* Php 8 compatibility +* Upgraded php version requirements +* Added Watermark with images +* Improved download to browser method + v1.0.11 * Bug AuthException warning diff --git a/circle.yml b/circle.yml index a777d7b..e0a9ea9 100644 --- a/circle.yml +++ b/circle.yml @@ -1,3 +1,3 @@ machine: php: - version: 7.3 \ No newline at end of file + version: 7.4 \ No newline at end of file diff --git a/composer.json b/composer.json index b08f408..4b1f418 100644 --- a/composer.json +++ b/composer.json @@ -21,10 +21,19 @@ } }, "require": { - "php": ">=7.3", - "ext-curl": "*" + "php": ">=7.4", + "ext-curl": "*", + "ext-openssl": "*", + "firebase/php-jwt": "^6.0", + "guzzlehttp/guzzle": "^7.4" }, "require-dev": { - "phpunit/phpunit": "^9.4" + "phpunit/phpunit": "^9.5", + "vimeo/psalm": "^4.21" + }, + "config": { + "allow-plugins": { + "composer/package-versions-deprecated": true + } } } diff --git a/init.php b/init.php deleted file mode 100755 index b95f912..0000000 --- a/init.php +++ /dev/null @@ -1,42 +0,0 @@ - - - - tests - - - - - lib - - - - - - \ No newline at end of file diff --git a/psalm.xml b/psalm.xml new file mode 100644 index 0000000..7c0333d --- /dev/null +++ b/psalm.xml @@ -0,0 +1,15 @@ + + + + + + + + + diff --git a/readme.md b/readme.md index f58408b..3510ce3 100644 --- a/readme.md +++ b/readme.md @@ -14,12 +14,10 @@ Develop and automate PDF processing tasks like Compress PDF, Merge PDF, Split PD ## Requirements -PHP 7.3 and later. +PHP 7.4 and later. ## Install -### Using composer - You can install the library via [Composer](http://getcomposer.org/). Run the following command: ```bash @@ -32,15 +30,6 @@ To use the library, use Composer's [autoload](https://getcomposer.org/doc/00-int require_once('vendor/autoload.php'); ``` - -### Manual Installation - -If you do not wish to use Composer, you can download the [latest release](https://github.com/ilovepdf/ilovepdf-php/releases). Then, to use the library, include the `init.php` file. - -```php -require_once('/path/to/ilovepdf-php/init.php'); -``` - ## Getting Started Simple usage looks like: diff --git a/src/Element.php b/src/Element.php index 1f3fab7..51c5e49 100644 --- a/src/Element.php +++ b/src/Element.php @@ -156,7 +156,7 @@ public function setText($text) } /** - * @param strig $image + * @param string $image */ public function setImage($image) { diff --git a/src/Exceptions/ExtendedException.php b/src/Exceptions/ExtendedException.php index b611f51..8b45e6b 100644 --- a/src/Exceptions/ExtendedException.php +++ b/src/Exceptions/ExtendedException.php @@ -15,15 +15,16 @@ class ExtendedException extends Exception * @param string $message * @param int $code * @param Exception|null $previous - * @param $response + * @param $responseBody */ - public function __construct($message, $response, $code = 0, Exception $previous = null) + public function __construct($message, $responseBody, $code = 0, $previous = null) { - if (isset($response->body->error) && $response->body->error->type) { - $this->type = $response->body->error->type; + if(!$code){$code = 0;} + if (isset($responseBody->error) && $responseBody->error->type) { + $this->type = $responseBody->error->type; } - if (isset($response->body->error->param)) { - $this->params = $response->body->error->param; + if (isset($responseBody->error->param)) { + $this->params = $responseBody->error->param; } if ($this->params) { if (is_array($this->params)) { @@ -60,6 +61,9 @@ public function __construct($message, $response, $code = 0, Exception $previous */ public function getErrors() { + if(!is_countable($this->params)){ + return []; + } return $this->params; } diff --git a/src/Http/Client.php b/src/Http/Client.php new file mode 100644 index 0000000..d5c9371 --- /dev/null +++ b/src/Http/Client.php @@ -0,0 +1,43 @@ + self::$allowRedirects, + 'http_errors' => false, + 'verify' => self::$verify, + ]; + + $this->client = new \GuzzleHttp\Client(array_merge_recursive($defaultParams, $params)); + } + + public function request(string $method, $uri = '', array $options = []): ResponseInterface + { + return $this->client->request($method, $uri, $options); + } + + public static function setAllowRedirects(bool $follow) + { + self::$allowRedirects = $follow; + } + + /** + * @param $verify + */ + public static function setVerify($verify) + { + self::$verify = $verify; + } +} \ No newline at end of file diff --git a/src/Http/ClientException.php b/src/Http/ClientException.php new file mode 100644 index 0000000..8d42093 --- /dev/null +++ b/src/Http/ClientException.php @@ -0,0 +1,7 @@ +secretKey; + return $this->secretKey ?? ''; } /** @@ -117,7 +116,6 @@ public function getJWT() $secret = $this->getSecretKey(); $currentTime = time(); - $request = ''; $hostInfo = ''; // Merge token with presets not to miss any params in custom @@ -134,7 +132,7 @@ public function getJWT() $token['jti'] = $this->getPublicKey(); // Set encryptKey - if ($this->getFileEncryption()){ + if ($this->getFileEncryption()) { $token['file_encryption_key'] = $this->getEncrytKey(); } @@ -152,11 +150,10 @@ public static function getTokenAlgorithm() return 'HS256'; } - /** * @param string $method * @param string $endpoint - * @param string $body + * @param mixed $body * * @return mixed response from server * @@ -164,82 +161,97 @@ public static function getTokenAlgorithm() * @throws ProcessException * @throws UploadException */ - public function sendRequest($method, $endpoint, $body=null, $start=false) + public function sendRequest($method, $endpoint, $params = [], $start = false) { - $to_server = self::$startServer; + $to_server = self::getStartServer(); if (!$start && !is_null($this->getWorkerServer())) { $to_server = $this->workerServer; } - - if ($endpoint == 'process' || $endpoint == 'upload' || strpos($endpoint, 'download/') === 0) { - Request::timeout($this->timeoutLarge); - } else { - Request::timeout($this->timeout); + $timeout = ($endpoint == 'process' || $endpoint == 'upload' || strpos($endpoint, 'download/') === 0) ? $this->timeoutLarge : $this->timeout; + $requestConfig = [ + 'connect_timeout' => $timeout, + 'headers' => ['Authorization' => 'Bearer ' . $this->getJWT(), 'Accept' => 'application/json'], + ]; + + $requestParams = $requestConfig; + if($params) { + $requestParams = array_merge($requestConfig, $params); } - $response = Request::$method($to_server . '/v1/' . $endpoint, array( - 'Accept' => 'application/json', - 'Authorization' => 'Bearer ' . $this->getJWT() - ), $body); + $client = new Client($params); + $error = null; - if ($response->code != '200' && $response->code != '201') { - if ($response->code == 401) { - throw new AuthException($response->body->name, $response->code, null, $response); + try { + $response = $client->request($method, $to_server . '/v1/' . $endpoint, $requestParams); + } catch (ClientException $e) { + $response = $e->getResponse(); + $error = $e; + } + $responseCode = $response->getStatusCode(); + if ($responseCode != '200' && $responseCode != '201') { + $responseBody = json_decode($response->getBody()); + if ($responseCode == 401) { + throw new AuthException($responseBody->name, $responseBody, $responseCode); } if ($endpoint == 'upload') { - if(is_string($response->body)){ - throw new UploadException("Upload error", $response, $response->code, null); + if (is_string($responseBody)) { + throw new UploadException("Upload error", $responseBody, $responseCode); } - throw new UploadException($response->body->error->message, $response, $response->code, null); - } - elseif ($endpoint == 'process') { - throw new ProcessException($response->body->error->message, $response, $response->code, null); - } - elseif (strpos($endpoint, 'download')===0) { - throw new DownloadException($response->body->error->message, $response, $response->code, null); - } - else{ - if ($response->code == 429) { + throw new UploadException($responseBody->error->message, $responseBody, $responseCode); + } elseif ($endpoint == 'process') { + throw new ProcessException($responseBody->error->message, $responseBody, $responseCode); + } elseif (strpos($endpoint, 'download') === 0) { + throw new DownloadException($responseBody->error->message, $responseBody, $responseCode); + } else { + if ($response->getStatusCode() == 429) { throw new \Exception('Too Many Requests'); } - if ($response->code == 400) { - if(strpos($endpoint, 'task')!=-1){ + if ($response->getStatusCode() == 400) { + if (strpos($endpoint, 'task') != -1) { throw new TaskException('Invalid task id'); } throw new \Exception('Bad Request'); } - if(isset($response->body->error) && isset($response->body->error->message)) { - throw new \Exception($response->body->error->message); + if (isset($responseBody->error) && isset($responseBody->error->message)) { + throw new \Exception($responseBody->error->message); } throw new \Exception('Bad Request'); } } + return $response; } /** - * @param string $tool Api tool to use - * @param bool $makeStart Set to false for chained tasks, because we don't need the start + * @param string $tool Api tool to use + * @param bool $makeStart Set to false for chained tasks, because we don't need the start * * @return mixed Return implemented Task class for specified tool * * @throws \Exception */ - public function newTask($tool='', $makeStart = true) + public function newTask($tool = '', $makeStart = true) { $classname = '\\Ilovepdf\\' . ucwords(strtolower($tool)) . 'Task'; if (!class_exists($classname)) { - throw new \InvalidArgumentException(); + throw new \InvalidArgumentException('Invalid tool'); } - return new $classname($this->getPublicKey(), $this->getSecretKey(), $makeStart); + + if($tool == ''){ + $makeStart = false; + } + + $task = new $classname($this->getPublicKey(), $this->getSecretKey(), $makeStart); + return $task; } - public static function setStartServer($server){ + public static function setStartServer($server) + { self::$startServer = $server; } - - public static function getStartServer(){ + public function getStartServer() + { return self::$startServer; } @@ -260,17 +272,15 @@ public function setWorkerServer($workerServer) } - /** * @param boolean $value */ - public function setFileEncryption($value, $encryptKey=null) + public function setFileEncryption($value, $encryptKey = null) { $this->encrypted = $value; - if($this->encrypted){ + if ($this->encrypted) { $this->setEncryptKey($encryptKey); - } - else{ + } else { $this->encryptKey = null; } } @@ -295,9 +305,9 @@ public function getEncrytKey() /** * @param mixed $encrytKey */ - public function setEncryptKey($encryptKey=null) + public function setEncryptKey($encryptKey = null) { - if($encryptKey==null){ + if ($encryptKey == null) { $encryptKey = IlovepdfTool::rand_sha1(32); } $len = strlen($encryptKey); @@ -314,37 +324,37 @@ public function getStatus($server, $taskId) { $workerServer = $this->getWorkerServer(); $this->setWorkerServer($server); - $response = $this->sendRequest('get', 'task/'.$taskId); + $response = $this->sendRequest('get', 'task/' . $taskId); $this->setWorkerServer($workerServer); - - return $response->body; + return json_decode($response->getBody()); } /** * @param $verify */ - public function verifySsl($verify){ - Request::verifyPeer($verify); - Request::verifyHost($verify); + public function verifySsl($verify) + { + Client::setVerify($verify); } /** * @param $follow */ - public function followLocation($follow){ - Request::followLocation($follow); + public function followLocation($follow) + { + Client::setAllowRedirects($follow); } - private function getUpdatedInfo(){ + private function getUpdatedInfo() + { $data = array('v' => self::VERSION); - $body = Body::Form($data); + $body = ['form_params' => $data]; $response = self::sendRequest('get', 'info', $body); - $this->info = $response->body; + $this->info = json_decode($response->getBody()); return $this->info; } - /** * @return object */ diff --git a/src/Lib/JWT.php b/src/Lib/JWT.php deleted file mode 100644 index 5ae6531..0000000 --- a/src/Lib/JWT.php +++ /dev/null @@ -1,366 +0,0 @@ - - * @author Anant Narayanan - * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD - * @link https://github.com/firebase/php-jwt - */ -class JWT -{ - - /** - * When checking nbf, iat or expiration times, - * we want to provide some extra leeway time to - * account for clock skew. - */ - public static $leeway = 0; - - /** - * Allow the current timestamp to be specified. - * Useful for fixing a value within unit testing. - * - * Will default to PHP time() value if null. - */ - public static $timestamp = null; - - public static $supported_algs = array( - 'HS256' => array('hash_hmac', 'SHA256'), - 'HS512' => array('hash_hmac', 'SHA512'), - 'HS384' => array('hash_hmac', 'SHA384'), - 'RS256' => array('openssl', 'SHA256'), - ); - - /** - * Decodes a JWT string into a PHP object. - * - * @param string $jwt The JWT - * @param string|array $key The key, or map of keys. - * If the algorithm used is asymmetric, this is the public key - * @param array $allowed_algs List of supported verification algorithms - * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' - * - * @return object The JWT's payload as a PHP object - * - * @throws UnexpectedValueException Provided JWT was invalid - * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed - * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' - * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' - * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim - * - * @uses jsonDecode - * @uses urlsafeB64Decode - */ - public static function decode($jwt, $key, $allowed_algs = array()) - { - $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp; - - if (empty($key)) { - throw new InvalidArgumentException('Key may not be empty'); - } - if (!is_array($allowed_algs)) { - throw new InvalidArgumentException('Algorithm not allowed'); - } - $tks = explode('.', $jwt); - if (count($tks) != 3) { - throw new UnexpectedValueException('Wrong number of segments'); - } - list($headb64, $bodyb64, $cryptob64) = $tks; - if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) { - throw new UnexpectedValueException('Invalid header encoding'); - } - if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) { - throw new UnexpectedValueException('Invalid claims encoding'); - } - $sig = static::urlsafeB64Decode($cryptob64); - - if (empty($header->alg)) { - throw new UnexpectedValueException('Empty algorithm'); - } - if (empty(static::$supported_algs[$header->alg])) { - throw new UnexpectedValueException('Algorithm not supported'); - } - if (!in_array($header->alg, $allowed_algs)) { - throw new UnexpectedValueException('Algorithm not allowed'); - } - if (is_array($key) || $key instanceof \ArrayAccess) { - if (isset($header->kid)) { - $key = $key[$header->kid]; - } else { - throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); - } - } - - // Check the signature - if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { - throw new SignatureInvalidException('Signature verification failed'); - } - - // Check if the nbf if it is defined. This is the time that the - // token can actually be used. If it's not yet that time, abort. - if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) { - throw new BeforeValidException( - 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf) - ); - } - - // Check that this token has been created before 'now'. This prevents - // using tokens that have been created for later use (and haven't - // correctly used the nbf claim). - if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) { - throw new BeforeValidException( - 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat) - ); - } - - // Check if this token has expired. - if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { - throw new ExpiredException('Expired token'); - } - - return $payload; - } - - /** - * Converts and signs a PHP object or array into a JWT string. - * - * @param object|array $payload PHP object or array - * @param string $key The secret key. - * If the algorithm used is asymmetric, this is the private key - * @param string $alg The signing algorithm. - * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' - * @param mixed $keyId - * @param array $head An array with header elements to attach - * - * @return string A signed JWT - * - * @uses jsonEncode - * @uses urlsafeB64Encode - */ - public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) - { - $header = array('typ' => 'JWT', 'alg' => $alg); - if ($keyId !== null) { - $header['kid'] = $keyId; - } - if ( isset($head) && is_array($head) ) { - $header = array_merge($head, $header); - } - $segments = array(); - $segments[] = static::urlsafeB64Encode(static::jsonEncode($header)); - $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload)); - $signing_input = implode('.', $segments); - - $signature = static::sign($signing_input, $key, $alg); - $segments[] = static::urlsafeB64Encode($signature); - - return implode('.', $segments); - } - - /** - * Sign a string with a given key and algorithm. - * - * @param string $msg The message to sign - * @param string|resource $key The secret key - * @param string $alg The signing algorithm. - * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' - * - * @return string An encrypted message - * - * @throws DomainException Unsupported algorithm was specified - */ - public static function sign($msg, $key, $alg = 'HS256') - { - if (empty(static::$supported_algs[$alg])) { - throw new DomainException('Algorithm not supported'); - } - list($function, $algorithm) = static::$supported_algs[$alg]; - switch($function) { - case 'hash_hmac': - return hash_hmac($algorithm, $msg, $key, true); - case 'openssl': - $signature = ''; - $success = openssl_sign($msg, $signature, $key, $algorithm); - if (!$success) { - throw new DomainException("OpenSSL unable to sign data"); - } else { - return $signature; - } - } - } - - /** - * Verify a signature with the message, key and method. Not all methods - * are symmetric, so we must have a separate verify and sign method. - * - * @param string $msg The original message (header and body) - * @param string $signature The original signature - * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key - * @param string $alg The algorithm - * - * @return bool - * - * @throws DomainException Invalid Algorithm or OpenSSL failure - */ - private static function verify($msg, $signature, $key, $alg) - { - if (empty(static::$supported_algs[$alg])) { - throw new DomainException('Algorithm not supported'); - } - - list($function, $algorithm) = static::$supported_algs[$alg]; - switch($function) { - case 'openssl': - $success = openssl_verify($msg, $signature, $key, $algorithm); - if (!$success) { - throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string()); - } else { - return $signature; - } - case 'hash_hmac': - default: - $hash = hash_hmac($algorithm, $msg, $key, true); - if (function_exists('hash_equals')) { - return hash_equals($signature, $hash); - } - $len = min(static::safeStrlen($signature), static::safeStrlen($hash)); - - $status = 0; - for ($i = 0; $i < $len; $i++) { - $status |= (ord($signature[$i]) ^ ord($hash[$i])); - } - $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); - - return ($status === 0); - } - } - - /** - * Decode a JSON string into a PHP object. - * - * @param string $input JSON string - * - * @return object Object representation of JSON string - * - * @throws DomainException Provided string was invalid JSON - */ - public static function jsonDecode($input) - { - if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { - /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you - * to specify that large ints (like Steam Transaction IDs) should be treated as - * strings, rather than the PHP default behaviour of converting them to floats. - */ - $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING); - } else { - /** Not all servers will support that, however, so for older versions we must - * manually detect large ints in the JSON string and quote them (thus converting - *them to strings) before decoding, hence the preg_replace() call. - */ - $max_int_length = strlen((string) PHP_INT_MAX) - 1; - $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input); - $obj = json_decode($json_without_bigints); - } - - if (function_exists('json_last_error') && $errno = json_last_error()) { - static::handleJsonError($errno); - } elseif ($obj === null && $input !== 'null') { - throw new DomainException('Null result with non-null input'); - } - return $obj; - } - - /** - * Encode a PHP object into a JSON string. - * - * @param object|array $input A PHP object or array - * - * @return string JSON representation of the PHP object or array - * - * @throws DomainException Provided object could not be encoded to valid JSON - */ - public static function jsonEncode($input) - { - $json = json_encode($input); - if (function_exists('json_last_error') && $errno = json_last_error()) { - static::handleJsonError($errno); - } elseif ($json === 'null' && $input !== null) { - throw new DomainException('Null result with non-null input'); - } - return $json; - } - - /** - * Decode a string with URL-safe Base64. - * - * @param string $input A Base64 encoded string - * - * @return string A decoded string - */ - public static function urlsafeB64Decode($input) - { - $remainder = strlen($input) % 4; - if ($remainder) { - $padlen = 4 - $remainder; - $input .= str_repeat('=', $padlen); - } - return base64_decode(strtr($input, '-_', '+/')); - } - - /** - * Encode a string with URL-safe Base64. - * - * @param string $input The string you want encoded - * - * @return string The base64 encode of what you passed in - */ - public static function urlsafeB64Encode($input) - { - return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); - } - - /** - * Helper method to create a JSON error. - * - * @param int $errno An error number from json_last_error() - * - * @return void - */ - private static function handleJsonError($errno) - { - $messages = array( - JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', - JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', - JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON' - ); - throw new DomainException( - isset($messages[$errno]) - ? $messages[$errno] - : 'Unknown JSON error: ' . $errno - ); - } - - /** - * Get the number of bytes in cryptographic strings. - * - * @param string - * - * @return int - */ - private static function safeStrlen($str) - { - if (function_exists('mb_strlen')) { - return mb_strlen($str, '8bit'); - } - return strlen($str); - } -} diff --git a/src/Request/Body.php b/src/Request/Body.php deleted file mode 100644 index daa3f64..0000000 --- a/src/Request/Body.php +++ /dev/null @@ -1,66 +0,0 @@ - $file) { - $data[$name] = call_user_func(array(__CLASS__, 'File'), $file); - } - } - - return $data; - } -} diff --git a/src/Request/Method.php b/src/Request/Method.php deleted file mode 100644 index 7ddf026..0000000 --- a/src/Request/Method.php +++ /dev/null @@ -1,75 +0,0 @@ - '', - 'pass' => '', - 'method' => CURLAUTH_BASIC - ); - - private static $proxy = array( - 'port' => false, - 'tunnel' => false, - 'address' => false, - 'type' => CURLPROXY_HTTP, - 'auth' => array( - 'user' => '', - 'pass' => '', - 'method' => CURLAUTH_BASIC - ) - ); - - /** - * Set JSON decode mode - * - * @param bool $assoc When TRUE, returned objects will be converted into associative arrays. - * @param integer $depth User specified recursion depth. - * @param integer $options Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats) - * @return array - */ - public static function jsonOpts($assoc = false, $depth = 512, $options = 0) - { - return self::$jsonOpts = array($assoc, $depth, $options); - } - - /** - * Verify SSL peer - * - * @param bool $enabled enable SSL verification, by default is true - * @return bool - */ - public static function verifyPeer($enabled) - { - return self::$verifyPeer = $enabled; - } - - /** - * Verify SSL host - * - * @param bool $enabled enable SSL host verification, by default is true - * @return bool - */ - public static function verifyHost($enabled) - { - return self::$verifyHost = $enabled; - } - - /** - * Follow location option - * - * @param bool $enabled enable follow location, by default is true - * @return bool - */ - public static function followLocation($enabled) - { - return self::$followLocation = $enabled; - } - - /** - * Set a timeout - * - * @param integer $seconds timeout value in seconds - * @return integer - */ - public static function timeout($seconds) - { - return self::$socketTimeout = $seconds; - } - - /** - * Set default headers to send on every request - * - * @param array $headers headers array - * @return array - */ - public static function defaultHeaders($headers) - { - return self::$defaultHeaders = array_merge(self::$defaultHeaders, $headers); - } - - /** - * Set a new default header to send on every request - * - * @param string $name header name - * @param string $value header value - * @return string - */ - public static function defaultHeader($name, $value) - { - return self::$defaultHeaders[$name] = $value; - } - - /** - * Clear all the default headers - */ - public static function clearDefaultHeaders() - { - return self::$defaultHeaders = array(); - } - - /** - * Set curl options to send on every request - * - * @param array $options options array - * @return array - */ - public static function curlOpts($options) - { - return self::mergeCurlOptions(self::$curlOpts, $options); - } - - /** - * Set a new default header to send on every request - * - * @param string $name header name - * @param string $value header value - * @return string - */ - public static function curlOpt($name, $value) - { - return self::$curlOpts[$name] = $value; - } - - /** - * Clear all the default headers - */ - public static function clearCurlOpts() - { - return self::$curlOpts = array(); - } - - - /** - * Send a GET request to a URL - * - * @param string $url URL to send the GET request to - * @param array $headers additional headers to send - * @param mixed $parameters parameters to send in the querystring - * @param string $username Authentication username (deprecated) - * @param string $password Authentication password (deprecated) - * @return Response - */ - public static function get($url, $headers = array(), $parameters = null, $username = null, $password = null) - { - return self::send(Method::GET, $url, $parameters, $headers, $username, $password); - } - - /** - * Send a HEAD request to a URL - * @param string $url URL to send the HEAD request to - * @param array $headers additional headers to send - * @param mixed $parameters parameters to send in the querystring - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response - */ - public static function head($url, $headers = array(), $parameters = null, $username = null, $password = null) - { - return self::send(Method::HEAD, $url, $parameters, $headers, $username, $password); - } - - /** - * Send a OPTIONS request to a URL - * @param string $url URL to send the OPTIONS request to - * @param array $headers additional headers to send - * @param mixed $parameters parameters to send in the querystring - * @param string $username Basic Authentication username - * @param string $password Basic Authentication password - * @return Response - */ - public static function options($url, $headers = array(), $parameters = null, $username = null, $password = null) - { - return self::send(Method::OPTIONS, $url, $parameters, $headers, $username, $password); - } - - /** - * Send a CONNECT request to a URL - * @param string $url URL to send the CONNECT request to - * @param array $headers additional headers to send - * @param mixed $parameters parameters to send in the querystring - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response - */ - public static function connect($url, $headers = array(), $parameters = null, $username = null, $password = null) - { - return self::send(Method::CONNECT, $url, $parameters, $headers, $username, $password); - } - - /** - * Send POST request to a URL - * @param string $url URL to send the POST request to - * @param array $headers additional headers to send - * @param mixed $body POST body data - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response response - */ - public static function post($url, $headers = array(), $body = null, $username = null, $password = null) - { - return self::send(Method::POST, $url, $body, $headers, $username, $password); - } - - /** - * Send DELETE request to a URL - * @param string $url URL to send the DELETE request to - * @param array $headers additional headers to send - * @param mixed $body DELETE body data - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response - */ - public static function delete($url, $headers = array(), $body = null, $username = null, $password = null) - { - return self::send(Method::DELETE, $url, $body, $headers, $username, $password); - } - - /** - * Send PUT request to a URL - * @param string $url URL to send the PUT request to - * @param array $headers additional headers to send - * @param mixed $body PUT body data - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response - */ - public static function put($url, $headers = array(), $body = null, $username = null, $password = null) - { - return self::send(Method::PUT, $url, $body, $headers, $username, $password); - } - - /** - * Send PATCH request to a URL - * @param string $url URL to send the PATCH request to - * @param array $headers additional headers to send - * @param mixed $body PATCH body data - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response - */ - public static function patch($url, $headers = array(), $body = null, $username = null, $password = null) - { - return self::send(Method::PATCH, $url, $body, $headers, $username, $password); - } - - /** - * Send TRACE request to a URL - * @param string $url URL to send the TRACE request to - * @param array $headers additional headers to send - * @param mixed $body TRACE body data - * @param string $username Basic Authentication username (deprecated) - * @param string $password Basic Authentication password (deprecated) - * @return Response - */ - public static function trace($url, $headers = array(), $body = null, $username = null, $password = null) - { - return self::send(Method::TRACE, $url, $body, $headers, $username, $password); - } - - /** - * This function is useful for serializing multidimensional arrays, and avoid getting - * the 'Array to string conversion' notice - * @param array|object $data array to flatten. - * @param bool|string $parent parent key or false if no parent - * @return array - */ - public static function buildHTTPCurlQuery($data, $parent = false) - { - $result = array(); - - if (is_object($data)) { - $data = get_object_vars($data); - } - - foreach ($data as $key => $value) { - if ($parent) { - $new_key = sprintf('%s[%s]', $parent, $key); - } else { - $new_key = $key; - } - - if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) { - $result = array_merge($result, self::buildHTTPCurlQuery($value, $new_key)); - } else { - $result[$new_key] = $value; - } - } - - return $result; - } - - /** - * Send a cURL request - * @param \Ilovepdf\Method|string $method HTTP method to use - * @param string $url URL to send the request to - * @param mixed $body request body - * @param array $headers additional headers to send - * @param string $username Authentication username (deprecated) - * @param string $password Authentication password (deprecated) - * @return Response - * @throws \Ilovepdf\Exception if a cURL error occurs - */ - public static function send($method, $url, $body = null, $headers = array(), $username = null, $password = null) - { - self::$handle = curl_init(); - - if ($method !== Method::GET) { - if ($method === Method::POST) { - curl_setopt(self::$handle, CURLOPT_POST, true); - } else { - curl_setopt(self::$handle, CURLOPT_CUSTOMREQUEST, $method); - } - - curl_setopt(self::$handle, CURLOPT_POSTFIELDS, $body); - } elseif (is_array($body)) { - if (strpos($url, '?') !== false) { - $url .= '&'; - } else { - $url .= '?'; - } - - $url .= urldecode(http_build_query(self::buildHTTPCurlQuery($body))); - } - - $curl_base_options = [ - CURLOPT_URL => self::encodeUrl($url), - CURLOPT_RETURNTRANSFER => true, - CURLOPT_MAXREDIRS => 10, - CURLOPT_HTTPHEADER => self::getFormattedHeaders($headers), - CURLOPT_HEADER => true, - CURLOPT_SSL_VERIFYPEER => self::$verifyPeer, - //CURLOPT_SSL_VERIFYHOST accepts only 0 (false) or 2 (true). Future versions of libcurl will treat values 1 and 2 as equals - CURLOPT_SSL_VERIFYHOST => self::$verifyHost === false ? 0 : 2, - // If an empty string, '', is set, a header containing all supported encoding types is sent - CURLOPT_ENCODING => '' - ]; - - curl_setopt_array(self::$handle, self::mergeCurlOptions($curl_base_options, self::$curlOpts)); - - if (self::$followLocation == true) { - @curl_setopt(self::$handle, CURLOPT_FOLLOWLOCATION, true); - } - - if (self::$socketTimeout !== null) { - curl_setopt(self::$handle, CURLOPT_TIMEOUT, self::$socketTimeout); - } - - if (self::$cookie) { - curl_setopt(self::$handle, CURLOPT_COOKIE, self::$cookie); - } - - if (self::$cookieFile) { - curl_setopt(self::$handle, CURLOPT_COOKIEFILE, self::$cookieFile); - curl_setopt(self::$handle, CURLOPT_COOKIEJAR, self::$cookieFile); - } - - // supporting deprecated http auth method - if (!empty($username)) { - curl_setopt_array(self::$handle, array( - CURLOPT_HTTPAUTH => CURLAUTH_BASIC, - CURLOPT_USERPWD => $username . ':' . $password - )); - } - - if (!empty(self::$auth['user'])) { - curl_setopt_array(self::$handle, array( - CURLOPT_HTTPAUTH => self::$auth['method'], - CURLOPT_USERPWD => self::$auth['user'] . ':' . self::$auth['pass'] - )); - } - - if (self::$proxy['address'] !== false) { - curl_setopt_array(self::$handle, array( - CURLOPT_PROXYTYPE => self::$proxy['type'], - CURLOPT_PROXY => self::$proxy['address'], - CURLOPT_PROXYPORT => self::$proxy['port'], - CURLOPT_HTTPPROXYTUNNEL => self::$proxy['tunnel'], - CURLOPT_PROXYAUTH => self::$proxy['auth']['method'], - CURLOPT_PROXYUSERPWD => self::$proxy['auth']['user'] . ':' . self::$proxy['auth']['pass'] - )); - } - - $response = curl_exec(self::$handle); - $error = curl_error(self::$handle); - $info = self::getInfo(); - - if ($error) { - if (strpos($error, 'SSL certificate problem')) { - throw new \Exception($error . ' Try using method verifySsl to false: "$ilovepdf->verifySsl(false)"'); - } - throw new \Exception($error); - } - - // Split the full response in its headers and body - $header_size = $info['header_size']; - $header = substr($response, 0, $header_size); - $body = substr($response, $header_size); - $httpCode = $info['http_code']; - - return new Response($httpCode, $body, $header, self::$jsonOpts); - } - - public static function getInfo($opt = false) - { - if ($opt) { - $info = curl_getinfo(self::$handle, $opt); - } else { - $info = curl_getinfo(self::$handle); - } - - return $info; - } - - public static function getCurlHandle() - { - return self::$handle; - } - - public static function getFormattedHeaders($headers) - { - $formattedHeaders = array(); - - $combinedHeaders = array_change_key_case(array_merge(self::$defaultHeaders, (array)$headers)); - - foreach ($combinedHeaders as $key => $val) { - $formattedHeaders[] = self::getHeaderString($key, $val); - } - - if (!array_key_exists('user-agent', $combinedHeaders)) { - $formattedHeaders[] = 'user-agent: unirest-php/2.0'; - } - - if (!array_key_exists('expect', $combinedHeaders)) { - $formattedHeaders[] = 'expect:'; - } - - return $formattedHeaders; - } - - private static function getArrayFromQuerystring($query) - { - $query = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function ($match) { - return bin2hex(urldecode($match[0])); - }, $query); - - parse_str($query, $values); - - return array_combine(array_map('hex2bin', array_keys($values)), $values); - } - - /** - * Ensure that a URL is encoded and safe to use with cURL - * @param string $url URL to encode - * @return string - */ - private static function encodeUrl($url) - { - $url_parsed = parse_url($url); - - $scheme = $url_parsed['scheme'] . '://'; - $host = $url_parsed['host']; - $port = (isset($url_parsed['port']) ? $url_parsed['port'] : null); - $path = (isset($url_parsed['path']) ? $url_parsed['path'] : null); - $query = (isset($url_parsed['query']) ? $url_parsed['query'] : null); - - if ($query !== null) { - $query = '?' . http_build_query(self::getArrayFromQuerystring($query)); - } - - if ($port && $port[0] !== ':') { - $port = ':' . $port; - } - - $result = $scheme . $host . $port . $path . $query; - return $result; - } - - private static function getHeaderString($key, $val) - { - $key = trim(strtolower($key)); - return $key . ': ' . $val; - } - - /** - * @param array $existing_options - * @param array $new_options - * @return array - */ - private static function mergeCurlOptions(&$existing_options, $new_options) - { - $existing_options = $new_options + $existing_options; - return $existing_options; - } -} diff --git a/src/Request/Response.php b/src/Request/Response.php deleted file mode 100644 index d80c97f..0000000 --- a/src/Request/Response.php +++ /dev/null @@ -1,78 +0,0 @@ -code = $code; - $this->headers = $this->parseHeaders($headers); - $this->raw_body = $raw_body; - $this->body = $raw_body; - - // make sure raw_body is the first argument - array_unshift($json_args, $raw_body); - - if (function_exists('json_decode')) { - $json = call_user_func_array('json_decode', $json_args); - - if (json_last_error() === JSON_ERROR_NONE) { - $this->body = $json; - } - } - } - - /** - * if PECL_HTTP is not available use a fall back function - * - * thanks to ricardovermeltfoort@gmail.com - * http://php.net/manual/en/function.http-parse-headers.php#112986 - * @param string $raw_headers raw headers - * @return array - */ - private function parseHeaders($raw_headers) - { - if (function_exists('http_parse_headers')) { - return http_parse_headers($raw_headers); - } else { - $key = ''; - $headers = array(); - - foreach (explode("\n", $raw_headers) as $i => $h) { - $h = explode(':', $h, 2); - - if (isset($h[1])) { - if (!isset($headers[$h[0]])) { - $headers[$h[0]] = trim($h[1]); - } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } else { - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); - } - - $key = $h[0]; - } else { - if (substr($h[0], 0, 1) == "\t") { - $headers[$key] .= "\r\n\t".trim($h[0]); - } elseif (!$key) { - $headers[0] = trim($h[0]); - } - } - } - - return $headers; - } - } -} diff --git a/src/Task.php b/src/Task.php index d539052..90aa8b9 100644 --- a/src/Task.php +++ b/src/Task.php @@ -2,11 +2,11 @@ namespace Ilovepdf; -use http\Exception\InvalidArgumentException; +use Ilovepdf\Exceptions\AuthException; +use Ilovepdf\Exceptions\ProcessException; use Ilovepdf\Exceptions\StartException; use Ilovepdf\Exceptions\PathException; -use Ilovepdf\Request\Body; -use Ilovepdf\Request\Request; +use Ilovepdf\Exceptions\UploadException; /** * Class Ilovepdf @@ -17,7 +17,6 @@ class Task extends Ilovepdf { // @var string The Ilovepdf API Task ID. public $task = null; - //private $server = null; public $files = []; public $tool; public $packaged_filename; @@ -60,24 +59,26 @@ class Task extends Ilovepdf * @param null $publicKey * @param null $secretKey */ - function __construct($publicKey, $secretKey, $makeStart=false) + function __construct($publicKey, $secretKey, $makeStart = false) { parent::__construct($publicKey, $secretKey); - if($makeStart) { + if ($makeStart) { $this->start(); } } - public function start(){ - $data = array('v' => self::VERSION); - $body = Body::Form($data); - $response = parent::sendRequest('get', 'start/' . $this->tool, $body); - if (empty($response->body->server)) { + public function start() + { + $data = ['v' => self::VERSION]; + + $response = parent::sendRequest('get', 'start/' . $this->tool, $data); + $responseBody = json_decode($response->getBody()); + if (empty($responseBody->server)) { throw new StartException('no server assigned on start'); }; - $this->setWorkerServer('https://' . $response->body->server); - $this->setTask($response->body->task); + $this->setWorkerServer('https://' . $responseBody->server); + $this->setTask($responseBody->task); } public function next($nextTool): Task @@ -87,12 +88,12 @@ public function next($nextTool): Task 'task' => $this->getTaskId(), 'tool' => $nextTool ]; - $body = Body::Form($data); + $body = ['form_params' => $data]; try { $response = parent::sendRequest('post', 'task/next', $body); - - if (empty($response->body->task)) { + $responseBody = json_decode($response->getBody()); + if (empty($responseBody->task)) { throw new StartException('No task assigned on chained start'); }; } catch (\Exception $e) { @@ -101,10 +102,11 @@ public function next($nextTool): Task $next = $this->newTask($nextTool); $next->setWorkerServer($this->getWorkerServer()); - $next->setTask($response->body->task); + + $next->setTask($responseBody->task); //add files chained - foreach ($response->body->files as $serverFilename => $fileName) { + foreach ($responseBody->files as $serverFilename => $fileName) { $next->files[] = new File($serverFilename, $fileName); } @@ -141,12 +143,12 @@ public function getFilesArray() return $filesArray; } - public function getStatus($server=null, $taskId=null) + public function getStatus($server = null, $taskId = null) { $server = $server ? $server : $this->getWorkerServer(); $taskId = $taskId ? $taskId : $this->getTaskId(); - if($server==null || $taskId==null){ + if ($server == null || $taskId == null) { throw new \Exception('Cannot get status if no file is uploaded'); } return parent::getStatus($this->getWorkerServer(), $this->getTaskId()); @@ -181,21 +183,32 @@ public function addFileFromUrl($url) * * @return File * - * @throws Exceptions\AuthException - * @throws Exceptions\ProcessException + * @throws AuthException + * @throws ProcessException * @throws UploadException */ public function uploadFile($task, $filepath) { - if(!file_exists($filepath)){ - throw new \InvalidArgumentException('File '.$filepath.' does not exists'); + if (!file_exists($filepath)) { + throw new \InvalidArgumentException('File ' . $filepath . ' does not exists'); } - $data = array('task' => $task, 'v'=> self::VERSION); - $files = array('file' => $filepath); - $body = Body::multipart($data, $files); + + $body = [ + 'multipart' => [ + [ + 'Content-type' => 'multipart/form-data', + 'name' => 'file', + 'contents' => fopen($filepath, 'r'), + 'filename' => basename($filepath) + ], + ['name' => 'task', 'contents' => $task], + ['name' => 'v', 'contents' => self::VERSION] + ], + ]; $response = $this->sendRequest('post', 'upload', $body); - return new File($response->body->server_filename, basename($filepath)); + $responseBody = json_decode($response->getBody()); + return new File($responseBody->server_filename, basename($filepath)); } /** @@ -221,7 +234,8 @@ public function addElementFileFromUrl($url) */ public function delete() { - $response = $this->sendRequest('delete', 'task/'.$this->getTaskId()); + $response = $this->sendRequest('delete', 'task/' . $this->getTaskId()); + $this->result = json_decode($response->getBody()); return $this; } @@ -231,16 +245,24 @@ public function delete() * * @return File * - * @throws Exceptions\AuthException - * @throws Exceptions\ProcessException + * @throws AuthException + * @throws ProcessException * @throws UploadException */ public function uploadUrl($task, $url) { - $data = array('task' => $task, 'cloud_file' => $url, 'v'=> self::VERSION); - $body = Body::Form($data); + //$data = ['task' => $task, 'cloud_file' => $url, 'v' => self::VERSION]; + //$body = ['form_data' => $data]; + $body = [ + 'multipart' => [ + ['name' => 'task', 'contents' => $task], + ['name' => 'v', 'contents' => self::VERSION], + ['name' => 'cloud_file', 'contents' => $url] + ], + ]; $response = parent::sendRequest('post', 'upload', $body); - return new File($response->body->server_filename, basename($url)); + $responseBody = json_decode($response->getBody()); + return new File($responseBody->server_filename, basename($url)); } /** @@ -249,8 +271,8 @@ public function uploadUrl($task, $url) */ public function download($path = null) { - if($path!=null && !is_dir($path)){ - if(pathinfo($path, PATHINFO_EXTENSION) == ''){ + if ($path != null && !is_dir($path)) { + if (pathinfo($path, PATHINFO_EXTENSION) == '') { throw new PathException('Invalid download path. Use method setOutputFilename() to set the output file name.'); } throw new PathException('Invalid download path. Set a valid folder path to download the file.'); @@ -273,7 +295,7 @@ public function download($path = null) public function blob() { $this->downloadFile($this->task); - return $this->outputFile; + return $this->outputFile; } /** @@ -287,27 +309,24 @@ public function toBrowser() // Try to change headers. try { - if($this->outputFileType == 'pdf'){ + if ($this->outputFileType == 'pdf') { header("Content-type:application/pdf"); - header("Content-Disposition:attachment;filename=\"".$this->outputFileName."\""); - } - else{ + header("Content-Disposition:attachment;filename=\"" . $this->outputFileName . "\""); + } else { if (function_exists('mb_strlen')) { $size = mb_strlen($this->outputFile, '8bit'); } else { $size = strlen($this->outputFile); } header('Content-Type: application/zip'); - header("Content-Disposition: attachment; filename=\"".$this->outputFileName."\""); - header("Content-Length: ".$size); + header("Content-Disposition: attachment; filename=\"" . $this->outputFileName . "\""); + header("Content-Length: " . $size); } - } - catch (\Throwable $th) { + } catch (\Throwable $th) { // Do nothing. // This happens when output stream is opened and headers // are changed. - } - finally { + } finally { echo $this->outputFile; } } @@ -316,25 +335,25 @@ public function toBrowser() * @param string $task * @param string $path * - * @throws Exceptions\AuthException - * @throws Exceptions\ProcessException - * @throws Exceptions\UploadException + * @throws AuthException + * @throws ProcessException + * @throws UploadException */ private function downloadFile($task) { - $data = array('v'=> self::VERSION); - $body = Body::Form($data); + $data = array('v' => self::VERSION); + $body = ['form_params' => $data]; $response = parent::sendRequest('get', 'download/' . $task, $body); + $responseHeaders = $response->getHeaders(); + - if(preg_match("/filename\*\=utf-8\'\'([\W\w]+)/", $response->headers['Content-Disposition'], $matchesUtf)){ + if (preg_match("/filename\*\=utf-8\'\'([\W\w]+)/", $responseHeaders['Content-Disposition'][0], $matchesUtf)) { $filename = urldecode(str_replace('"', '', $matchesUtf[1])); - } - else { - preg_match('/ .*filename=\"([\W\w]+)\"/', $response->headers['Content-Disposition'], $matches); + } else { + preg_match('/ .*filename=\"([\W\w]+)\"/', $responseHeaders['Content-Disposition'][0], $matches); $filename = str_replace('"', '', $matches[1]); } - - $this->outputFile = $response->raw_body; + $this->outputFile = $response->getBody()->getContents(); $this->outputFileName = $filename; $this->outputFileType = pathinfo($this->outputFileName, PATHINFO_EXTENSION); } @@ -364,13 +383,13 @@ public function getEncrypted($value) */ public function execute() { - if($this->task===null){ + if ($this->task === null) { throw new \Exception('Current task not exists'); } $data = array_merge( $this->__toArray(), - array('task' => $this->task, 'files' => $this->files, 'v'=> self::VERSION) + ['task' => $this->task, 'files' => $this->files, 'v' => self::VERSION] ); //clean unwanted vars to be sent @@ -378,16 +397,17 @@ public function execute() unset($data['timeout']); unset($data['timeDelay']); - $body = Body::multipart($data); + $body = ['form_params' => $data]; - $response = parent::sendRequest('post', 'process', urldecode(http_build_query($body))); + $response = parent::sendRequest('post', 'process', $body); - $this->result = $response->body; + $this->result = json_decode($response->getBody()); return $this; } - public function __toArray () { + public function __toArray() + { return call_user_func('get_object_vars', $this); } @@ -421,10 +441,11 @@ public function setOutputFilename($filename) * @throws Exceptions\UploadException * @throws \Exception */ - public function deleteFile($file){ + public function deleteFile($file) + { if (($key = array_search($file, $this->files)) !== false) { - $body = Body::multipart(['task'=>$this->getTaskId(), 'server_filename'=>$file->server_filename, 'v'=> self::VERSION]); - $this->sendRequest('delete', 'upload/'.$this->getTaskId().'/'.$file->server_filename, $body); + $body = ['form_params' => ['task' => $this->getTaskId(), 'server_filename' => $file->server_filename, 'v' => self::VERSION]]; + $this->sendRequest('delete', 'upload/' . $this->getTaskId() . '/' . $file->server_filename, $body); unset($this->files[$key]); } return $this; @@ -436,9 +457,10 @@ public function deleteFile($file){ * * @return Task */ - public function checkValues($value, $allowedValues){ - if(!in_array($value, $allowedValues)){ - throw new \InvalidArgumentException('Invalid '.$this->tool.' value "'.$value.'". Must be one of: '.implode(',', $allowedValues)); + public function checkValues($value, $allowedValues) + { + if (!in_array($value, $allowedValues)) { + throw new \InvalidArgumentException('Invalid ' . $this->tool . ' value "' . $value . '". Must be one of: ' . implode(',', $allowedValues)); } } @@ -509,9 +531,9 @@ public function ignorePassword($value) * @param boolean $value * @return Task */ - public function setFileEncryption($value, $encryptKey=null) + public function setFileEncryption($value, $encryptKey = null) { - if(count($this->files)>0){ + if (count($this->files) > 0) { throw new \Exception('Encrypth mode cannot be set after file upload'); } @@ -562,7 +584,8 @@ public function setCustomString($customString) * * @throws \Exception */ - public function listTasks($tool=null, $status=null, $customInt=null, $page=null){ + public function listTasks($tool = null, $status = null, $customInt = null, $page = null) + { $this->checkValues($status, $this->statusValues); @@ -571,15 +594,14 @@ public function listTasks($tool=null, $status=null, $customInt=null, $page=null) 'status' => $status, 'custom_int' => $customInt, 'page' => $page, - 'v'=> self::VERSION, - 'secret_key'=>$this->getSecretKey() + 'v' => self::VERSION, + 'secret_key' => $this->getSecretKey() ]; - $body = Body::multipart($data); + $body = ['form_params' => $data]; $response = parent::sendRequest('post', 'task', $body, true); - - $this->result = $response->body; + $this->result = json_decode($response->getBody()); return $this->result; } diff --git a/src/WatermarkTask.php b/src/WatermarkTask.php index 484a792..2ed7222 100644 --- a/src/WatermarkTask.php +++ b/src/WatermarkTask.php @@ -23,7 +23,7 @@ class WatermarkTask extends Task public $text; /** - * @var strig + * @var string */ public $image; @@ -139,7 +139,7 @@ public function setText($text) } /** - * @param strig $image + * @param string $image */ public function setImage($image) { @@ -290,7 +290,7 @@ public function setLayer($layer) public function addElement($element) { - if (is_a($element, 'Element')) { + if (is_a($element, \Ilovepdf\Element::class)) { $this->elements[] = $element; } elseif (is_array($element)) { $this->elements[] = new Element($element); diff --git a/tests/bootstrap.no_autoload.php b/tests/bootstrap.no_autoload.php deleted file mode 100755 index 4e9dcfc..0000000 --- a/tests/bootstrap.no_autoload.php +++ /dev/null @@ -1,3 +0,0 @@ -