diff --git a/PlagScan/API.php b/PlagScan/API.php index bb222cb4a67b0f642c291e85f43233d23b7531be..9a596c3fe1095c2a6a0849a3bd7b63b1c8155f44 100644 --- a/PlagScan/API.php +++ b/PlagScan/API.php @@ -52,15 +52,11 @@ class API */ public function request(string $endPoint, string $requestType, string $accessToken = '', array $data = []) { - $ch = curl_init(); - $url = $this->connection . '/' . $endPoint; - if ($accessToken) { $url .= '?access_token=' . $accessToken; } - if ($requestType === 'GET' || $requestType === 'PATCH') { foreach ($data as $key => $value) { $url .= '&' . $key . '=' . $value; @@ -70,21 +66,21 @@ class API } $data = []; } - $curlopt = [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CUSTOMREQUEST => $requestType, ]; - if (!empty($data)) { - $curlopt = [CURLOPT_POSTFIELDS => $data] + $curlopt; + if(isset($data['fileUpload'])){ + $curlopt = $this->createFileDataParams($data) + $curlopt; + } else { + $curlopt = [CURLOPT_POSTFIELDS => $data] + $curlopt; + } } curl_setopt_array($ch, $curlopt); - $response = curl_exec($ch); curl_close($ch); - $response = json_decode($response, true) ?? $response; if (isset($response['data'])) { return $response['data']; @@ -94,4 +90,40 @@ class API } return $response; } + + /** + * Creates a string for fileuploads. + * + * @param array $data + * @return array + */ + private function createFileDataParams(array $data){ + $string = ""; + $id = uniqid(); + foreach ($data as $key => $param) { + if ($key !== 'fileUpload') { + $string .= + "---------------$id\r\n" + . "Content-Disposition: form-data; name=\"$key\"\r\n" + . "\r\n$param\r\n"; + } + } + $fn = end(explode('/',$data['fileUpload'])); + $mime = mime_content_type($data['fileUpload']); + $content = file_get_contents($data['fileUpload']); + $string .= + "---------------$id\r\n" + . "Content-Disposition: form-data; name=\"fileUpload\"; filename=\"$fn\"\r\n" + . "Content-Type: $mime\r\n" + . "Content-Transfer-Encoding: binary\r\n" + . "\r\n$content\r\n" + . "---------------$id--\r\n"; + return [ + CURLOPT_POSTFIELDS => $string, + CURLOPT_HTTPHEADER => [ + "Content-Type: multipart/form-data; boundary=-------------$id", + "Content-Length: " . strlen($string) + ] + ]; + } } \ No newline at end of file