Exemple #1
0
 public function testCURLFile()
 {
     $file = File::add(UPLOAD_FIXTURE);
     if (PHP_MAJOR_VERSION === 5 && PHP_MINOR_VERSION === 4) {
         $this->assertEquals($file, sprintf('@%s;filename=%s;type=', UPLOAD_FIXTURE, basename(UPLOAD_FIXTURE)));
     } else {
         $this->assertTrue($file instanceof \CURLFile);
     }
 }
 /**
  * The text should be provided as multipart/form-data with the key 'text'. Files can be uploaded.
  * @param  string     $text     Required parameter: Supply text to be classified.
  * @return mixed response from the API call*/
 public function createReturnEnglishGeneralSentimentMultipartForm($text)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/sentiment';
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('user-agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'X-Mashape-Key' => $this->xMashapeKey);
     //prepare parameters
     $parameters = array("file" => File::add($text));
     //prepare API request
     $request = Unirest::post($queryUrl, $headers, $parameters);
     //and invoke the API call request to fetch the response
     $response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code < 200 || $response->code > 206) {
         //[200,206] = HTTP OK
         throw new APIException("HTTP Response Not OK", $response->code);
     }
     return $response->body;
 }
 /**
  * Create a new project
  * @param  string     $callbackUrl            Required parameter: Optional. If you provide a callback URL, we will send POST callbacks when the status of the current project is changed. Possible status changes are, 'translated', 'proofread', 'completed'.
  * @param  array      $custom                 Required parameter: Optional. This is a consistent custom data parameter that will be given to you in the response across every request of this project model. Values should be provided like this, custom[my_key] = my_value.
  * @param  string     $document              Required parameter: Optional. You can add as many files as you want in documents[] parameter. Or you add your documents later in separate calls.
  * @param  string     $glossary             Required parameter: Optional. Only one glossary is supported at the moment.
  * @param  string     $sourceLanguage         Required parameter: TODO: type description here
  * @param  string     $styleguide            Required parameter: Optional. You can add as many files as you want in styleguides[] parameter. Or you add your style guides later in separate calls.
  * @param  array      $targetLanguages        Required parameter: TODO: type description here
  * @return mixed response from the API call*/
 public function createProject($sourceLanguage, $targetLanguages, $callbackUrl = null, $custom = [], $document = null, $glossary = null, $styleguide = null)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/projects';
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('user-agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'Authorization' => sprintf('Bearer %1$s', Configuration::$oAuthAccessToken));
     //prepare parameters
     $parameters = array('source_language' => $sourceLanguage, 'target_languages' => array_values($targetLanguages), 'callback_url' => $callbackUrl, 'custom' => array_values($custom));
     if ($document) {
         $parameters['documents[]'] = File::add($document);
     }
     if ($glossary) {
         $parameters['glossaries[]'] = File::add($glossary);
     }
     if ($styleguide) {
         $parameters['styleguides[]'] = File::add($styleguide);
     }
     //prepare API request
     $request = Unirest::post($queryUrl, $headers, $parameters);
     //and invoke the API call request to fetch the response
     $response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('FileTooLarge FileTooSmall FileWasAlreadyUploaded', 400, $response->body);
     } else {
         if ($response->code == 405) {
             throw new APIException('UnsupportedDocumentFormat UnsupportedStyleGuideFormat UnsupportedGlossaryFormat', 405, $response->body);
         } else {
             if ($response->code == 406) {
                 throw new APIException('UnsupportedLanguage TooManyGlossaries ProjectAlreadyHasGlossary', 406, $response->body);
             } else {
                 if ($response->code == 500) {
                     throw new APIException('ProjectInsertFailed', 500, $response->body);
                 } else {
                     if ($response->code < 200 || $response->code > 206) {
                         //[200,206] = HTTP OK
                         throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                     }
                 }
             }
         }
     }
     return $response->body;
 }
 /**
  * Update the style guide. File name and contents will replaced with the new one.
  * @param  int        $projectId        Required parameter: Project ID
  * @param  int        $styleGuideId     Required parameter: Style guide ID
  * @param  string     $styleguides      Required parameter: Single file data. The name is plural to provide a consistent naming convention.
  * @return mixed response from the API call*/
 public function updateStyleGuide($projectId, $styleGuideId, $styleguide)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/projects/{projectId}/styleguides/{styleGuideId}';
     //process optional query parameters
     APIHelper::appendUrlWithTemplateParameters($queryBuilder, array('projectId' => $projectId, 'styleGuideId' => $styleGuideId));
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('user-agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'Authorization' => sprintf('Bearer %1$s', Configuration::$oAuthAccessToken));
     //prepare parameters
     $parameters = array("styleguides" => File::add($styleguide));
     //prepare API request
     $request = Unirest::put($queryUrl, $headers, $parameters);
     //and invoke the API call request to fetch the response
     $response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('FileTooLarge', 400, $response->body);
     } else {
         if ($response->code == 404) {
             throw new APIException('StyleGuideNotFound', 404, $response->body);
         } else {
             if ($response->code == 405) {
                 throw new APIException('UnsupportedStyleGuideFormat', 405, $response->body);
             } else {
                 if ($response->code == 409) {
                     throw new APIException('ProjectAlreadyStarted', 409, $response->body);
                 } else {
                     if ($response->code < 200 || $response->code > 206) {
                         //[200,206] = HTTP OK
                         throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                     }
                 }
             }
         }
     }
     return $response->body;
 }
Exemple #5
0
 /**
  * Método que executa a conversão do PDF para jpg
  * @return boolean Retorna TRUE em caso de sucesso ou FALSE em caso de erro
  * @throws \GGE\Lib\Base\Exception
  */
 public function converter()
 {
     if (is_null($this->pdf)) {
         throw new \GGE\Lib\Base\Exception("O arquivo PDF ainda não foi definido");
     }
     if (is_null($this->destino)) {
         throw new \GGE\Lib\Base\Exception("Ainda não foi definida uma pasta de destino para as imagens");
     }
     if (!\GGE\Lib\Filter\Types\String::validarTipo($this->mashapeKey)) {
         throw new \GGE\Lib\Base\Exception("A chave de acesso a API ainda não foi definida");
     }
     //
     $response = \Unirest\Request::post(self::URL, array("X-Mashape-Key" => "37y9fftqS2msh4qv4qXh4C8bWsg3p1AdUtVjsn9EnxMll5NYse"), array("pdf" => \Unirest\File::add($this->pdf), "resolution" => 150));
     die(var_dump($response));
     //Iniciando a conversão
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, self::URL);
     curl_setopt($ch, CURLOPT_HEADER, "X-Mashape-Key: <{$this->mashapeKey}>");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, array("pdf" => new \CURLFile($this->pdf, "application/pdf"), "resolution" => 150));
     $resultPost = curl_exec($ch);
     var_dump($resultPost);
     $responsePost = json_decode($resultPost);
     if (!$responsePost) {
         throw new \GGE\Lib\Base\Exception("Falha ao tentar converter o PDF. Erro no servidor remoto");
     }
     //Lendo e baixando as imagens resultantes
     curl_setopt($ch, CURLOPT_POST, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, array("id" => $responsePost->id, "key" => $responsePost->key));
     $resultGet = curl_exec($ch);
     $responseGet = json_decode($resultGet);
     if (!$responseGet) {
         throw new \GGE\Lib\Base\Exception("Falha ao tentar recuperar as imagens resultantes da conversão");
     }
     curl_close($ch);
     if ($responseGet->status != "done") {
         throw new \GGE\Lib\Base\Exception("Falha ao ler as imagens. O servidor retornou uma falha");
     }
     //Baixando as imagens para o servidor
     if (!file_exists($this->destino)) {
         //Caso a pasta de destino não exista
         if (!mkdir($this->destino, "0777", TRUE)) {
             throw new \GGE\Lib\Base\Exception("Falha ao tentar criar a pasta de destino");
         }
     }
     foreach ($responseGet->pictures as $pic) {
         if (!copy($pic, $this->destino, urldecode($pic))) {
             throw new \GGE\Lib\Base\Exception("Ocorreu um erro ao tentar copiar a imagem");
         }
     }
     return TRUE;
 }
 /**
  * Create or update your corporate account's global glossary
  * @param $glossary
  * @return mixed
  * @throws APIException
  * @throws \Exception
  */
 public function updateGlossary($glossary)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/glossary';
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('user-agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'Authorization' => sprintf('Bearer %1$s', Configuration::$oAuthAccessToken));
     //prepare parameters
     $parameters = array("glossary" => File::add($glossary));
     //prepare API request
     $request = Unirest::post($queryUrl, $headers, $parameters);
     //and invoke the API call request to fetch the response
     $response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('MissingCorporateAccount | FileTooSmall | FileTooLarge | NoFileUploaded', 400, $response->body);
     } else {
         if ($response->code == 405) {
             throw new APIException('UnsupportedGlossaryFormat', 405, $response->body);
         } else {
             if ($response->code < 200 || $response->code > 206) {
                 //[200,206] = HTTP OK
                 throw new APIException("HTTP Response Not OK", $response->code, $response->body);
             }
         }
     }
     return $response->body;
 }
 /**
  * Upload a proof for a specific address
  * @param   int $addressId    Required parameter: The address identifier
  * @param   string $proof    Required parameter: The proof to upload
  * @return StatusModel response from the API call*/
 public function addressProof($addressId, $proof)
 {
     //the base uri for api requests
     $queryBuilder = Configuration::BASEURI;
     //prepare query string for API call
     $queryBuilder = $queryBuilder . '/regulation/address/{addressId}/proof';
     //process optional query parameters
     APIHelper::appendUrlWithTemplateParameters($queryBuilder, array('addressId' => $addressId));
     //validate and preprocess url
     $queryUrl = APIHelper::cleanUrl($queryBuilder);
     //prepare headers
     $headers = array('User-Agent' => 'APIMATIC 2.0', 'Accept' => 'application/json', 'Content-type' => 'multipart/form-data; boundary=XXX');
     //prepare body
     $data = file_get_contents($proof);
     $uniProof = File::add($proof);
     $body = '--XXX' . "\n" . 'Content-ID: proofOfAddress' . "\n" . 'Content-Type:' . $uniProof->getMimeType() . "\n" . 'Content-Disposition: filename="' . $uniProof->getFilename() . '"' . "\n\n" . $data . "\n" . '--XXX--';
     //prepare API request
     $request = Unirest::put($queryUrl, $headers, $body);
     //and invoke the API call request to fetch the response
     $response = Unirest::getResponse($request);
     //Error handling using HTTP status codes
     if ($response->code < 200 || $response->code > 206) {
         //[200,206] = HTTP OK
         throw new APIException("HTTP Response Not OK", $response->code);
     }
     return $response->body;
 }
Exemple #8
0
 /**
  * Добавление фотографии.
  *
  * <h1>Примеры</h1>
  *
  * <h2>Простой пример загрузки фотографии</h2>
  * <code>
  * <?php
  * $photo = $api->createPhoto( array(
  *     'image' => $_SERVER['DOCUMENT_ROOT'] . '/assets/images/forest.jpg',
  *     'title' => 'Красивая фотография леса'
  * ) );
  * ?>
  * </code>
  *
  * <h2>Загрузка фотографии в определенный альбом</h2>
  * <code>
  * <?php
  * $photo = $api->createPhoto( array(
  *     'image' => $_SERVER['DOCUMENT_ROOT'] . '/assets/images/forest.jpg',
  *     'title' => 'Красивая фотография леса'
  * ), 123456 );
  * ?>
  * </code>
  *
  * <h2>Загрузка фотографии в с геопривязкой</h2>
  * <code>
  * <?php
  * $photo = $api->createPhoto( array(
  *     'image' => $_SERVER['DOCUMENT_ROOT'] . '/assets/images/forest.jpg',
  *     'title' => 'Красивая фотография леса',
  *     'geo'   => array(55.75396, 37.620393),
  *   //'geo'   => '55.75396 37.620393', // Можно задать и строкой
  * ) );
  * ?>
  * </code>
  *
  * <h2>Загрузка фотографии в с тегами</h2>
  * <code>
  * <?php
  * $photo = $api->createPhoto( array(
  *     'image' => $_SERVER['DOCUMENT_ROOT'] . '/assets/images/forest.jpg',
  *     'title' => 'Красивая фотография леса',
  *     'tags'  => array('Лес', 'Природа', 'Лето'),
  *   //'tags'  => 'Лес, Природа, Лето' // Можно задать и строкой
  * ) );
  * ?>
  * </code>
  *
  * <h2>Собираем все вместе</h2>
  * <code>
  * <?php
  * $photo = $api->createPhoto( array(
  *     'image'             => $_SERVER['DOCUMENT_ROOT'] . '/assets/images/forest.jpg',
  *     'title'             => 'Красивая фотография леса',
  *     'geo'               => array(55.75396, 37.620393),
  *     'tags'              => array('Лес', 'Природа', 'Лето'),
  *     'isAdult'           => false,     // Материал для взрослых
  *     'isDisableComments' => true,      // Указание на отключение комментариев
  *     'isHideOriginal'    => true,      // Указание на то, что нужно скрыть оригинал
  *     'access'            => 'private', // Может быть 'public', 'friends', 'private'
  * ) );
  * ?>
  * </code>
  *
  * @param array    $data         Данные фотографии
  *                               <ul>
  *                               <li> ['image']             <i><u>string</u></i>                       Путь до изображения <b>(Обязательный)</b></li>
  *                               <li> ['title']             <i><u>string</u></i>                       Название изображения <b>(Обязательный)</b></li>
  *                               <li> ['geo']               <i><u>string|string[]</u></i>              Координаты</li>
  *                               <li> ['tags']              <i><u>string|string[]</u></i>              Теги</li>
  *                               <li> ['isAdult']           <i><u>bool</u></i>                         Метриал для взрослых</li>
  *                               <li> ['isDisableComments'] <i><u>bool</u></i>                         Отключить комментарии</li>
  *                               <li> ['isHideOriginal']    <i><u>bool</u></i>                         Скрывать оригинал изображения</li>
  *                               <li> ['access']            <i><u>'public'|'friends'|'private'</u></i> Уровень доступа</li>
  *                               </ul>
  *
  * @param int|null $albumId      Id родительского альбома. Если null, то фото будет загружено в корень
  *
  * @return \Yandex\Fotki\Api\Photo Добавленная фотография
  * @throws \Yandex\Fotki\Exception\Api\Photo Если произошла ошибка во время загрузки фотографии
  */
 public function createPhoto($data, $albumId = null)
 {
     $url = $albumId ? sprintf("http://api-fotki.yandex.ru/api/users/%s/album/%s/photos/?format=json", $this->_login, intval($albumId)) : sprintf("http://api-fotki.yandex.ru/api/users/%s/photos/?format=json", $this->_login);
     $oAuthToken = $this->_transport->getOAuthToken();
     $fimpToken = $this->_transport->getFimpToken();
     $headers = array('Accept' => "application/json", 'Authorization' => $oAuthToken ? "OAuth {$oAuthToken}" : "FimpToken realm=\"fotki.yandex.ru\", token=\"{$fimpToken}\"");
     $response = Request::post($url, $headers, array('image' => File::add($data['image'])));
     if ($response->code === 201) {
         $responseBody = json_decode(json_encode($response->body), true);
         $photo = new Photo($this->_transport, $responseBody['links']['self']);
         $photo->initWithData($responseBody);
         //@formatter:off
         $photo->setTitle(isset($data['title']) ? $data['title'] : $photo->getTitle());
         $photo->setSummary(isset($data['summary']) ? $data['summary'] : $photo->getSummary());
         $photo->setIsAdult(isset($data['isAdult']) ? $data['isAdult'] : $photo->isAdult());
         $photo->setIsHideOriginal(isset($data['isHideOriginal']) ? $data['isHideOriginal'] : $photo->isHideOriginal());
         $photo->setIsDisableComments(isset($data['isDisableComments']) ? $data['isDisableComments'] : $photo->isDisableComments());
         $photo->setAccess(isset($data['access']) ? $data['access'] : $photo->getAccess());
         $photo->setGeo(isset($data['geo']) ? $data['geo'] : $photo->getGeo());
         $photo->setTags(isset($data['tags']) ? $data['tags'] : $photo->getTags());
         //@formatter:on
         return $this->updatePhoto($photo);
     } else {
         throw new \Yandex\Fotki\Exception\Api\Photo($response->body, $response->code);
     }
 }