/** * @param array $data * * @return array|string|null * * @throws \Exception */ public function send($data = null) { $request = new FormRequest($this->method, $this->resource, $this->host); if ($data) { $request->addFields($data); } try { $this->logger->addDebug('Request: ' . $request->getUrl()); /** @var Buzz\Message\Response $response */ $response = $this->client->send($request); $this->logger->addDebug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300) . PHP_EOL . var_export($this->client->getClient()->getInfo(), true)); } catch (\Exception $e) { switch ($e->getCode()) { case 28: $code = 504; break; default: $code = $e->getCode() >= 100 ? $e->getCode() : 500; } $this->logger->addCritical(PHP_EOL . __METHOD__ . sprintf('[%s/%s] %s', $e->getCode(), $code, $e->getMessage())); throw new WebGateException($e->getMessage(), $code, $e); } if ($response->getStatusCode() != 200) { throw new WebGateException(json_decode($response->getContent(), true), $response->getStatusCode()); } return json_decode($response->getContent(), true); }
/** * @param UserInterface $user * @param NamedNumberInterface[] $recipient * @param string $coverPage * @param string $coverPageText * @param string $resolution * @param \DateTime $sendTime * @param array $attachments * @return string */ public function sendFax(UserInterface $user, array $recipient, $coverPage, $coverPageText, $resolution, \DateTime $sendTime, array $attachments) { $form = new FormRequest(); $form->setResource(self::FAX_OUT_ENDPOINT); $recipients = array(); foreach ($recipient as $rec) { $recipients[] = $rec->getNumber() . ($rec->getName() ? '|' . $rec->getName() : ''); } $uploads = array(); foreach ($attachments as $attachment) { $uploads[] = new FormUpload($attachment); } $fields = array('Username' => $user->getUserNumber(), 'Password' => $user->getPassword(), 'Extension' => $user->getExtension(), 'Recipient' => $recipients, 'Coverpage' => $coverPage, 'Coverpagetext' => $coverPageText, 'Resolution' => $resolution, 'Sendtime' => $sendTime->format('d:m:y h:i'), 'Attachment' => $uploads); $form->addFields($fields); return $this->browser->post(self::FAX_OUT_ENDPOINT, $form->getHeaders(), $form->getContent()); }
/** * @param array $notification * * @return string */ public function notifyValidate(array $notification) { $request = new FormRequest(); $request->setField('cmd', self::CMD_NOTIFY_VALIDATE); $request->addFields($notification); $request->setMethod('POST'); $request->fromUrl($this->getIpnEndpoint()); $response = new Response(); $this->client->send($request, $response); if (false == $response->isSuccessful()) { throw HttpException::factory($request, $response); } if (self::NOTIFY_VERIFIED === $response->getContent()) { return self::NOTIFY_VERIFIED; } return self::NOTIFY_INVALID; }
/** * @param UploadedFile $file * @param string $clientName * @param string $context * * @return Response * * @throws MediaStorageClientApiException * * @todo config to $context */ public function sendFile(UploadedFile $file, $clientName, $context) { try { $request = new FormRequest(); $request->setHeaders(['headers' => 'enctype:multipart/form-data']); $request->setMethod($this->getClientsConfig($clientName, 'method') ? $this->getClientsConfig($clientName, 'method') : FormRequest::METHOD_POST); $request->setHost($this->getClientsConfig($clientName, 'base_url')); $formUpload = new FormUpload($file->getRealPath()); $formUpload->setFilename($file->getClientOriginalName()); $request->addFields(['binaryContent' => $formUpload, 'context' => $context]); $request->setResource($this->getClientsConfig($clientName, 'add_media_url')); $this->logger->debug('Send ' . $this->getClientsConfig($clientName, 'base_url') . $this->getClientsConfig($clientName, 'add_media_url')); //.' '.$request->getContent() /** @var Response $response */ $response = $this->client->send($request, null); $this->logger->debug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300)); } catch (\Exception $e) { throw new MediaStorageClientApiException($e->getMessage()); } return $response; }
public function testLoginWithExistingFrontendSession() { $loginFormResponse = $this->sendHttpRequest(new Request('GET', '/login', $this->getHttpHost())); $domDocument = $loginFormResponse->toDomDocument(); $xpath = new \DOMXPath($domDocument); $csrfDomElements = $xpath->query("//input[@name='_csrf_token']/@value"); self::assertGreaterThan(0, $csrfDomElements->length); $csrfTokenValue = $csrfDomElements->item(0)->nodeValue; $loginPostRequest = new FormRequest('POST', '/login', $this->getHttpHost()); $loginPostRequest->addFields(['_username' => $this->getLoginUsername(), '_password' => $this->getLoginPassword(), '_csrf_token' => $csrfTokenValue]); $loginResponse = $this->sendHttpRequest($loginPostRequest); if (!($sessionCookieHeader = $loginResponse->getHeader('set-cookie'))) { self::fail('No cookie in login response'); } list($sessionCookie) = explode(';', $sessionCookieHeader); $request = $this->createHttpRequest('POST', '/api/ezp/v2/user/sessions', 'SessionInput+json', 'Session+json'); $this->setSessionInput($request); $request->addHeader("Cookie: {$sessionCookie}"); $response = $this->sendHttpRequest($request); self::assertHttpResponseCodeEquals($response, 201); }
/** * Upload file- Not working!!!! - 408 error code... * * IMPROVE.... * * @param string $destFolderPath Target folder of the file * @param boolean $createParents Create parents folder if not exist * @param string $filePath Local file to upload * @param boolean $overwrite (Optionnal - Default null) null : Set error if file exists, true : overwrite file, false : skip upload if file exist * @param \DateTime $mtime (Optionnal) Set the modification time * @param \DateTime $crtime (Optionnal) Set the creation time * @param \DateTime $atime (Optionnal) Set the access time * * @return array Response of the request ("json_decoded") * * @throws PatbzhSynologyException In case synology api sends an error response * @throws \\InvalidArgumentException */ public function uploadFile($destFolderPath, $createParents, $filePath, $overwrite = null, $mtime = null, $crtime = null, $atime = null) { if (!is_string($destFolderPath)) { throw new \InvalidArgumentException('$destFolderPath should be a string'); } if (!is_string($filePath)) { throw new \InvalidArgumentException('$filePath should be a string'); } if (!is_bool($createParents)) { throw new \InvalidArgumentException('$createParents should be a boolean'); } if (!is_null($overwrite) && !is_bool($overwrite)) { throw new \InvalidArgumentException('$overwrite should be a boolean'); } if (!is_null($mtime) && !$mtime instanceof \DateTime) { throw new \InvalidArgumentException('$mtime should be a \\DateTime'); } if (!is_null($crtime) && !$crtime instanceof \DateTime) { throw new \InvalidArgumentException('$crtime should be a \\DateTime'); } if (!is_null($atime) && !$atime instanceof \DateTime) { throw new \InvalidArgumentException('$atime should be a \\DateTime'); } $additionalParams['dest_folder_path'] = $destFolderPath; if ($createParents) { $additionalParams['create_parents'] = 'true'; } if (!$createParents) { $additionalParams['create_parents'] = 'false'; } if (!is_null($overwrite) && $createParents) { $additionalParams['overwrite'] = 'true'; } if (!is_null($overwrite) && !$createParents) { $additionalParams['overwrite'] = 'false'; } if (!is_null($mtime)) { $additionalParams['mtime'] = $mtime->getTimestamp(); } if (!is_null($crtime)) { $additionalParams['crtime'] = $crtime->getTimestamp(); } if (!is_null($atime)) { $additionalParams['atime'] = $atime->getTimestamp(); } // $additionalParams['file'] = $file; $cgiPath = 'FileStation/api_upload.cgi'; $apiName = 'SYNO.FileStation.Upload'; $version = 1; // Check Available APIS if ($this->getIsQueriesValidated() && !in_array($apiName, array('SYNO.API.Auth', 'SYNO.API.Info')) && !isset($this->availableApis[$apiName])) { $this->retrieveAvailableApis($apiName); // Validate API information $calledApiInformation = $this->availableApis[$apiName]; if (is_null($calledApiInformation)) { throw new \RuntimeException('Unavailable API'); } if ($cgiPath != $calledApiInformation['ApiPath']) { throw new \RuntimeException('CGI Path problem [Requested: ' . $cgiPath . '][ServerVersion: ' . $calledApiInformation['ApiPath'] . ']'); } if ($calledApiInformation['MinVersion'] > $version) { throw new \RuntimeException('API Version issue [Requested: ' . $version . '][MinVersion: ' . $calledApiInformation['MinVersion'] . ']'); } if ($calledApiInformation['MaxVersion'] < $version) { throw new \RuntimeException('API Version issue [Requested: ' . $version . '][MaxVersion: ' . $calledApiInformation['MaxVersion'] . ']'); } } // Login if required if (!$this->isLoggedIn()) { $this->login(); } // Set "mandatory" parameters list $params = array('api' => $apiName, 'version' => $version, 'method' => 'upload'); if ($this->isLoggedIn()) { $params['_sid'] = $this->getSessionId(); } // Add additionnal parameters if ($additionalParams !== null) { $params = $params + $additionalParams; } // Set request $queryString = 'webapi/' . $cgiPath; $request = new FormRequest('POST', $queryString, $this->getBaseUrl()); $request->addFields($params); $uploadedFile = new FormUpload($filePath); $uploadedFile->setContentType('application/octet-stream'); $request->setField('file', $uploadedFile); $response = new Response(); // Handle request $this->httpClient->send($request, $response); // Check response $parsedResponse = json_decode($response->getContent(), true); // Throw exception in case of error if ($parsedResponse['success'] !== true) { throw new PatbzhSynologyException($this->getErrorMessage($parsedResponse['error']['code']) . ' (' . $parsedResponse['error']['code'] . ')', $parsedResponse['error']['code']); } // Return json_decoded response return $parsedResponse; }