public function Send(array $request)
 {
     $method = isset($request['METHOD']) ? strtoupper($request['METHOD']) : '';
     if ($method !== \Bitrix\Main\Web\HttpClient::HTTP_GET && $method !== \Bitrix\Main\Web\HttpClient::HTTP_POST) {
         throw new Bitrix\Main\ArgumentException("Could not find 'METHOD'.", 'request');
     }
     $path = isset($request['PATH']) && is_string($request['PATH']) ? $request['PATH'] : '';
     if ($path === '') {
         throw new Bitrix\Main\ArgumentException("Could not find 'PATH'.", 'request');
     }
     $postData = $method === \Bitrix\Main\Web\HttpClient::HTTP_POST && isset($request['BODY']) ? $request['BODY'] : null;
     if (!$this->client) {
         $this->client = new \Bitrix\Main\Web\HttpClient();
     }
     $this->client->setRedirect(false);
     if ($method === \Bitrix\Main\Web\HttpClient::HTTP_POST && is_array($postData)) {
         //Force UTF encoding
         $this->client->setCharset('UTF-8');
         if ((!isset($request['UTF']) || !$request['UTF']) && !defined('BX_UTF')) {
             $postData = \Bitrix\Main\Text\Encoding::convertEncodingArray($postData, SITE_CHARSET, 'UTF-8');
         }
     }
     $headers = isset($request['HEADERS']) ? $request['HEADERS'] : null;
     if (is_array($headers)) {
         foreach ($headers as $k => $v) {
             $this->client->setHeader($k, $v, true);
         }
     }
     if (!empty($this->cookies)) {
         $this->client->setCookies($this->cookies);
     }
     if ($this->enableProxy) {
         $this->client->setProxy($this->proxyServer, $this->proxyPort, $this->proxyUserName, $this->proxyUserPassword);
     }
     if ($this->userName !== '') {
         $this->client->setAuthorization($this->userName, $this->userPassword);
     }
     $this->client->setHeader('User-Agent', $this->userAgent, true);
     $absolutePath = $this->GetUrl() . $path;
     if (!$this->client->query($method, $absolutePath, $postData)) {
         $this->responseData = null;
         $this->errors = $this->client->getError();
     } else {
         /**@var \Bitrix\Main\Web\HttpHeaders*/
         $responseHeaders = $this->client->getHeaders();
         //STATUS.VERSION & STATUS.PHRASE are delcared for backward compatibility only.
         $this->responseData = array('STATUS' => array('VERSION' => '', 'CODE' => $this->client->getStatus(), 'PHRASE' => ''), 'CONTENT' => array('TYPE' => $this->client->getContentType(), 'ENCODING' => $this->client->getCharset()), 'HEADERS' => $responseHeaders, 'BODY' => $this->client->getResult());
         if ($responseHeaders->get('Set-Cookie', false) !== null) {
             $this->cookies = array_merge($this->cookies, $this->client->getCookies()->toArray());
             CCrmExternalSale::Update($this->externalSaleId, array('COOKIE' => serialize($this->cookies)));
         }
         $this->errors = array();
     }
     return $this->responseData;
 }
Пример #2
0
 protected function isAuthorized($strOfficeLogin, $strPassword, $url)
 {
     try {
         $http = new HttpClient();
         $http->setAuthorization($strOfficeLogin, $strPassword);
         $auth_status = trim($http->get($url));
         if ($http->getStatus() != '200') {
             return false;
         }
         return $auth_status == 'ok' || $auth_status == 'ok:' || preg_match('{^ok:(.+)$}', $auth_status);
     } catch (\Exception $e) {
         error_log('Office external auth error: ' . $e->getMessage());
     }
     return false;
 }
Пример #3
0
 public function downloadFile(array $fileData)
 {
     $accessToken = $this->getAccessToken();
     $fileId = $fileData['id'];
     $mimeType = $fileData['mimeType'];
     @set_time_limit(0);
     $file = $this->getFile($fileData);
     $http = new HttpClient(array('socketTimeout' => 10, 'version' => HttpClient::HTTP_1_1));
     if (!($file['content'] = $http->get($file['source']))) {
         return false;
     }
     // error checking
     if ($http->getStatus() != "200") {
         return false;
     }
     CWebDavTools::convertFromUtf8($file['name']);
     $this->recoverExtensionInName($file, $mimeType);
     return $file;
 }
Пример #4
0
 public function GetCurrentUserFriends($limit, &$next)
 {
     if ($this->access_token === false) {
         return false;
     }
     $http = new HttpClient();
     $http->setHeader('GData-Version', '3.0');
     $http->setHeader('Authorization', 'Bearer ' . $this->access_token);
     $url = static::FRIENDS_URL . '?';
     $limit = intval($limit);
     $next = intval($next);
     if ($limit > 0) {
         $url .= '&max-results=' . $limit;
     }
     if ($next > 0) {
         $url .= '&start-index=' . $next;
     }
     $result = $http->get($url);
     if (!defined("BX_UTF")) {
         $result = CharsetConverter::ConvertCharset($result, "utf-8", LANG_CHARSET);
     }
     if ($http->getStatus() == 200) {
         $obXml = new \CDataXML();
         if ($obXml->loadString($result)) {
             $tree = $obXml->getTree();
             $total = $tree->elementsByName("totalResults");
             $total = intval($total[0]->textContent());
             $limitNode = $tree->elementsByName("itemsPerPage");
             $next += intval($limitNode[0]->textContent());
             if ($next >= $total) {
                 $next = '__finish__';
             }
             $arFriends = array();
             $arEntries = $tree->elementsByName('entry');
             foreach ($arEntries as $entry) {
                 $arEntry = array();
                 $entryChildren = $entry->children();
                 foreach ($entryChildren as $child) {
                     $tag = $child->name();
                     switch ($tag) {
                         case 'category':
                         case 'updated':
                         case 'edited':
                             break;
                         case 'name':
                             $arEntry[$tag] = array();
                             foreach ($child->children() as $subChild) {
                                 $arEntry[$tag][$subChild->name()] = $subChild->textContent();
                             }
                             break;
                         case 'email':
                             if ($child->getAttribute('primary') == 'true') {
                                 $arEntry[$tag] = $child->getAttribute('address');
                             }
                             break;
                         default:
                             $tagContent = $tag == 'link' ? $child->getAttribute('href') : $child->textContent();
                             if ($child->getAttribute('rel')) {
                                 if (!isset($arEntry[$tag])) {
                                     $arEntry[$tag] = array();
                                 }
                                 $arEntry[$tag][preg_replace("/^[^#]*#/", "", $child->getAttribute('rel'))] = $tagContent;
                             } elseif (isset($arEntry[$tag])) {
                                 if (!is_array($arEntry[$tag][0]) || !isset($arEntry[$tag][0])) {
                                     $arEntry[$tag] = array($arEntry[$tag], $tagContent);
                                 } else {
                                     $arEntry[$tag][] = $tagContent;
                                 }
                             } else {
                                 $arEntry[$tag] = $tagContent;
                             }
                     }
                 }
                 if ($arEntry['email']) {
                     $arFriends[] = $arEntry;
                 }
             }
             return $arFriends;
         }
     }
     return false;
 }
Пример #5
0
 public static function authorize()
 {
     \CSocServAuthManager::SetUniqueKey();
     $redirectUri = static::getRedirectUri();
     $url = static::getEngine()->getInterface()->GetAuthUrl($redirectUri, "backurl=" . urlencode($redirectUri . '?check_key=' . $_SESSION["UNIQUE_KEY"]));
     $httpClient = new HttpClient(array("redirect" => false));
     $result = $httpClient->get($url);
     if ($httpClient->getStatus() == 302) {
         return array("location" => $httpClient->getHeaders()->get("Location"));
     }
     throw new SystemException("Wrong response: " . $result);
 }
Пример #6
0
 protected function checkHttpResponse(HttpClient $http)
 {
     $status = (int) $http->getStatus();
     if ($status === 401) {
         $this->errorCollection->add(array(new Error('Invalid credentials (401)', self::ERROR_CODE_INVALID_CREDENTIALS)));
     } elseif ($status === 403) {
         $headers = $http->getHeaders();
         $response = $http->getResult();
         $errorMessage = '';
         if ($response && is_string($response)) {
             $jsonResponse = Json::decode($response);
             if (isset($jsonResponse['error']['message'])) {
                 $errorMessage = $jsonResponse['error']['message'];
             }
             unset($jsonResponse, $response);
         }
         $headerAuthenticate = $headers->get('WWW-Authenticate');
         if (is_string($headerAuthenticate) && strpos($headerAuthenticate, 'insufficient') !== false) {
             $this->errorCollection->add(array(new Error('Insufficient scope (403)', self::ERROR_CODE_INSUFFICIENT_SCOPE)));
             return false;
         } elseif (strpos($errorMessage, 'The authenticated user has not installed the app with client') !== false) {
             $this->errorCollection->add(array(new Error('The authenticated user has not installed the app (403)', self::ERROR_CODE_NOT_INSTALLED_APP)));
         } elseif (strpos($errorMessage, 'The authenticated user has not granted the app') !== false) {
             $this->errorCollection->add(array(new Error('The authenticated user has not granted the app (403)', self::ERROR_CODE_NOT_GRANTED_APP)));
         } elseif (strpos($errorMessage, 'Invalid accessLevel') !== false) {
             $this->errorCollection->add(array(new Error('Invalid accessLevel (403)', self::ERROR_CODE_INVALID_ACCESS_LEVEL)));
         } elseif (strpos($errorMessage, 'is not properly configured as a Google Drive app') !== false) {
             $this->errorCollection->add(array(new Error('The app does not exist or is not properly configured as a Google Drive app (403)', self::ERROR_CODE_APP_NOT_CONFIGURED)));
         } elseif (strpos($errorMessage, 'is blacklisted') !== false) {
             $this->errorCollection->add(array(new Error('The app is blacklisted as a Google Drive app. (403)', self::ERROR_CODE_APP_IN_BLACKLIST)));
         } elseif ($errorMessage) {
             $this->errorCollection->add(array(new Error($errorMessage, self::ERROR_CODE_UNKNOWN)));
         }
     }
     if ($this->errorCollection->hasErrors()) {
         return false;
     }
     return parent::checkHttpResponse($http);
 }
Пример #7
0
 protected static function downloadFile($fileName, $storeAs, $skip404 = false, $storeTo = false)
 {
     // useless thing
     if (!$storeTo) {
         $storeTo = \CTempFile::GetDirectoryName(1);
     }
     $storeTo .= $storeAs;
     if (file_exists($storeTo)) {
         if (!is_writable($storeTo)) {
             throw new Main\SystemException('Cannot remove previous ' . $storeAs . ' file');
         }
         unlink($storeTo);
     }
     $query = 'http://' . self::DISTRIBUTOR_HOST . ':' . self::DISTRIBUTOR_PORT . self::REMOTE_PATH . $fileName;
     $client = new HttpClient();
     if (!$client->download($query, $storeTo)) {
         $eFormatted = array();
         foreach ($client->getError() as $code => $desc) {
             $eFormatted[] = trim($desc . ' (' . $code . ')');
         }
         throw new Main\SystemException('File download failed: ' . implode(', ', $eFormatted) . ' (' . $query . ')');
     }
     $status = intval($client->getStatus());
     if ($status != 200 && file_exists($storeTo)) {
         unlink($storeTo);
     }
     $okay = $status == 200 || $status == 404 && $skip404;
     // honestly we should check for all 2xx codes, but for now this is enough
     if (!$okay) {
         throw new Main\SystemException('File download failed: http error ' . $status . ' (' . $query . ')');
     }
     return filesize($storeTo);
 }
Пример #8
0
 public function finance_query($method, $masterToken, $operationNum, $param = array(), $skipRefreshAuth = false)
 {
     if ($this->engineSettings['AUTH']) {
         $http = new HttpClient();
         $http->setRedirect(false);
         $http->setHeader("Content-Type", "application/json; charset=utf-8");
         $auth = $this->getCurrentUser();
         $financeToken = hash("sha256", $masterToken . $operationNum . $method . $auth['login']);
         $postData = array("method" => $method, "finance_token" => $financeToken, "operation_num" => $operationNum, "locale" => $this->locale, "token" => $this->engineSettings['AUTH']['access_token']);
         if (!empty($param)) {
             $postData["param"] = $param;
         }
         $postData = YandexJson::encode($postData, JSON_UNESCAPED_UNICODE);
         $http->post(self::API_URL, $postData);
         if ($http->getStatus() == 401 && !$skipRefreshAuth) {
             if ($this->checkAuthExpired(false)) {
                 $this->query($method, $param, true);
             }
         }
         return $http;
     } else {
         throw new SystemException("No Yandex auth data");
     }
 }
Пример #9
0
 /**
  * Returns HttpClient object with query result
  *
  * @param string $scope Url to call
  * @param string $method HTTP method (GET/POST/PUT supported)
  * @param array|null $data Post data
  * @param bool $skipRefreshAuth Skip authorization refresh
  *
  * @returns \Bitrix\Main\Web\HttpClient
  * @throws SystemException
  */
 protected function query($scope, $method = "GET", $data = null, $skipRefreshAuth = false)
 {
     if ($this->engineSettings['AUTH']) {
         $http = new Web\HttpClient();
         $http->setHeader('Authorization', 'OAuth ' . $this->engineSettings['AUTH']['access_token']);
         $http->setRedirect(false);
         switch ($method) {
             case 'GET':
                 $http->get($scope);
                 break;
             case 'POST':
                 $http->post($scope, $data);
                 break;
             case 'PUT':
                 $http->query($method, $scope, $data);
                 break;
             case 'DELETE':
                 break;
         }
         if ($http->getStatus() == 401 && !$skipRefreshAuth) {
             if ($this->checkAuthExpired(false)) {
                 $this->query($scope, $method, $data, true);
             }
         }
         return $http;
     } else {
         throw new SystemException("No Yandex auth data");
     }
 }
Пример #10
0
 protected static function downloadFile($fileName, $storeAs, $skip404 = false)
 {
     $storeTo = $_SERVER['DOCUMENT_ROOT'] . self::LOCAL_PATH;
     if (file_exists($storeTo)) {
         if (!is_writable($storeTo)) {
             throw new Main\SystemException('Temporal directory is not writable by the current user');
         }
     } else {
         $dir = new IO\Directory($_SERVER['DOCUMENT_ROOT']);
         $dir->createSubdirectory(self::LOCAL_PATH);
     }
     $storeTo .= $storeAs;
     if (file_exists($storeTo)) {
         if (!is_writable($storeTo)) {
             throw new Main\SystemException('Cannot remove previous ' . $storeAs . ' file');
         }
         unlink($storeTo);
     }
     $query = 'http://' . self::DISTRIBUTOR_HOST . ':' . self::DISTRIBUTOR_PORT . self::REMOTE_PATH . $fileName;
     $client = new HttpClient();
     if (!$client->download($query, $storeTo)) {
         $eFormatted = array();
         foreach ($client->getError() as $code => $desc) {
             $eFormatted[] = trim($desc . ' (' . $code . ')');
         }
         throw new Main\SystemException('File download failed: ' . implode(', ', $eFormatted) . ' (' . $query . ')');
     }
     $status = intval($client->getStatus());
     if ($status != 200 && file_exists($storeTo)) {
         unlink($storeTo);
     }
     $okay = $status == 200 || $status == 404 && $skip404;
     // honestly we should check for all 2xx codes, but for now this is enough
     if (!$okay) {
         throw new Main\SystemException('File download failed: http error ' . $status . ' (' . $query . ')');
     }
     // charset conversion here?
     return filesize($storeTo);
 }
Пример #11
0
 protected function query($scope, $method = "GET", $data = null, $bSkipRefreshAuth = false, $contentType = 'application/json')
 {
     if ($this->engineSettings['AUTH']) {
         $http = new HttpClient();
         $http->setHeader("Authorization", 'Bearer ' . $this->engineSettings['AUTH']['access_token']);
         /*
         			$http->setAdditionalHeaders(
         				array(
         					'Authorization' => ,
         					'GData-Version' => '2'
         				)
         			);
         */
         switch ($method) {
             case 'GET':
                 $result = $http->get($scope);
                 break;
             case 'POST':
             case 'PUT':
                 $http->setHeader("Content-Type", $contentType);
                 $result = $http->query($method, $scope, $data);
                 break;
             case 'DELETE':
                 break;
         }
         if ($http->getStatus() == 401 && !$bSkipRefreshAuth) {
             if ($this->checkAuthExpired(true)) {
                 return $this->query($scope, $method, $data, true, $contentType);
             }
         }
         return $http;
     }
 }
Пример #12
0
 /**
  * @param HttpClient $http
  * @return bool
  */
 protected function checkHttpResponse(HttpClient $http)
 {
     $status = (int) $http->getStatus();
     if ($status === 401) {
         $this->errorCollection->add(array(new Error('Invalid credentials (401)', self::ERROR_CODE_INVALID_CREDENTIALS)));
         return false;
     } elseif ($status === 403) {
         $headers = $http->getHeaders();
         $headerAuthenticate = $headers->get('WWW-Authenticate');
         if (is_string($headerAuthenticate) && strpos($headerAuthenticate, 'insufficient') !== false) {
             $this->errorCollection->add(array(new Error('Insufficient scope (403)', self::ERROR_CODE_INSUFFICIENT_SCOPE)));
             return false;
         }
     } elseif (!($status >= 200 && $status < 300)) {
         $this->errorCollection->add(array(new Error("Invalid response status code ({$status})", self::ERROR_INVALID_RESPONSE_STATUS)));
         return false;
     }
     return true;
 }
Пример #13
0
 public function call($methodName, $additionalParams = null)
 {
     global $APPLICATION;
     if (!$this->access_token) {
         $interface = Service::getEngine()->getInterface();
         if (!$interface->checkAccessToken()) {
             if ($interface->getNewAccessToken()) {
                 Service::getEngine()->setAuthSettings($interface->getResult());
             } else {
                 return $interface->getResult();
             }
         }
         $this->access_token = $interface->getToken();
     }
     if ($this->access_token) {
         if (!is_array($additionalParams)) {
             $additionalParams = array();
         } else {
             $additionalParams = $APPLICATION->ConvertCharsetArray($additionalParams, LANG_CHARSET, "utf-8");
         }
         $additionalParams['auth'] = $this->access_token;
         $http = new HttpClient(array('socketTimeout' => $this->httpTimeout));
         $result = $http->post(CBitrixSeoOAuthInterface::URL . self::SERVICE_URL . $methodName, $additionalParams);
         /*			AddMessage2Log(array(
         				CBitrixSeoOAuthInterface::URL.self::SERVICE_URL.$methodName,
         				$additionalParams,
         				$http->getStatus(),
         				$result,
         			));*/
         $res = $this->prepareAnswer($result);
         if (!$res) {
             AddMessage2Log('Strange answer from Seo! ' . $http->getStatus() . ' ' . $result);
         }
         return $res;
     } else {
         throw new SystemException("No access token");
     }
 }
Пример #14
0
 /**
  * @param Uri $uri Absolute URL to get metadata for.
  * @return array|false
  */
 protected static function getRemoteUrlMetadata(Uri $uri)
 {
     $httpClient = new HttpClient();
     $httpClient->setTimeout(5);
     $httpClient->setStreamTimeout(5);
     if (!$httpClient->query('GET', $uri->getUri())) {
         return false;
     }
     if ($httpClient->getStatus() !== 200) {
         return false;
     }
     $htmlContentType = strtolower($httpClient->getHeaders()->getContentType());
     if ($htmlContentType !== 'text/html') {
         return static::getFileMetadata($httpClient->getEffectiveUrl(), $httpClient->getHeaders());
     }
     $html = $httpClient->getResult();
     $htmlDocument = new HtmlDocument($html, $uri);
     $htmlDocument->setEncoding($httpClient->getCharset());
     ParserChain::extractMetadata($htmlDocument);
     $metadata = $htmlDocument->getMetadata();
     if (is_array($metadata) && static::validateRemoteMetadata($metadata)) {
         if (isset($metadata['IMAGE']) && static::getOptionSaveImages()) {
             $metadata['IMAGE_ID'] = static::saveImage($metadata['IMAGE']);
             unset($metadata['IMAGE']);
         }
         return $metadata;
     }
     return false;
 }