示例#1
0
 /**
  * Downloads and parses HTML's document metadata, formatted with oEmbed standard.
  *
  * @param HtmlDocument $document HTML document.
  */
 public function handle(HtmlDocument $document)
 {
     if (!$this->detectOembedLink($document) || strlen($this->metadataUrl) == 0) {
         return;
     }
     $httpClient = new HttpClient();
     $rawMetadata = $httpClient->get($this->metadataUrl);
     if ($rawMetadata === false) {
         return;
     }
     $parsedMetadata = $this->parseMetadata($rawMetadata);
     if ($parsedMetadata !== false) {
         if (strlen($this->metadataEncoding) > 0 && $document->getEncoding() !== $this->metadataEncoding) {
             $parsedMetadata = Encoding::convertEncodingArray($parsedMetadata, $this->metadataEncoding, $document->getEncoding());
         }
         if ($document->getTitle() == '' && $parsedMetadata['title'] != '') {
             $document->setTitle($parsedMetadata['title']);
         }
         if ($document->getImage() == '' && $parsedMetadata['thumbnail_url'] != '') {
             $document->setImage($parsedMetadata['thumbnail_url']);
         }
         if ($document->getEmdbed() == '' && $parsedMetadata['html'] != '') {
             $document->setEmbed($parsedMetadata['html']);
         }
     }
 }
 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;
 }
示例#3
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;
 }
示例#4
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;
 }
示例#5
0
 protected function query($url)
 {
     if ($this->access_token === false) {
         return false;
     }
     $http = new HttpClient();
     $http->setHeader("authorization", "Bearer " . $this->access_token);
     $result = $http->get($url);
     if (!defined("BX_UTF")) {
         $result = CharsetConverter::ConvertCharset($result, "utf-8", LANG_CHARSET);
     }
     $result = CUtil::JsObjectToPhp($result);
     return $result;
 }
示例#6
0
 private function getFileSizeInternal($downloadUrl)
 {
     $accessToken = $this->getAccessToken();
     $http = new HttpClient(array('socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1));
     $http->setHeader('Authorization', "Bearer {$accessToken}");
     if ($http->query('HEAD', $downloadUrl) === false) {
         $errorString = implode('; ', array_keys($http->getError()));
         $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_GET_METADATA)));
         return null;
     }
     if (!$this->checkHttpResponse($http)) {
         return null;
     }
     return $http->getHeaders()->get('Content-Length');
 }
示例#7
0
 public function GetAppInfo()
 {
     if ($this->access_token === false) {
         return false;
     }
     $h = new \Bitrix\Main\Web\HttpClient();
     $h->setTimeout($this->httpTimeout);
     $result = $h->post(static::TOKENINFO_URL . '?access_token=' . urlencode($this->access_token));
     $result = \Bitrix\Main\Web\Json::decode($result);
     if (is_array($result) && $result["audience"]) {
         $result["id"] = $result["audience"];
     }
     return $result;
 }
示例#8
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);
 }
示例#9
0
 /**
  * Lists folder contents
  * @param $path
  * @param $folderId
  * @return mixed
  */
 public function listFolder($path, $folderId)
 {
     if ($path === '/') {
         $folderId = '0';
     }
     $http = new HttpClient(array('socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1));
     $http->setHeader('Content-Type', 'application/json; charset=UTF-8');
     $http->setHeader('Authorization', "Bearer {$this->getAccessToken()}");
     if ($http->get(self::API_URL_V2 . "/folders/{$folderId}/items?fields=name,size,modified_at") === false) {
         $errorString = implode('; ', array_keys($http->getError()));
         $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_LIST_FOLDER)));
         return null;
     }
     if (!$this->checkHttpResponse($http)) {
         return null;
     }
     $items = Json::decode($http->getResult());
     if ($items === null) {
         $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON)));
         return null;
     }
     if (!isset($items['entries'])) {
         $this->errorCollection->add(array(new Error('Could not find items in response', self::ERROR_HTTP_LIST_FOLDER)));
         return null;
     }
     $reformatItems = array();
     foreach ($items['entries'] as $item) {
         $isFolder = $item['type'] === 'folder';
         $dateTime = new \DateTime($item['modified_at']);
         $reformatItems[$item['id']] = array('id' => $item['id'], 'name' => $item['name'], 'type' => $isFolder ? 'folder' : 'file', 'size' => $isFolder ? '' : \CFile::formatSize($item['size']), 'sizeInt' => $isFolder ? '' : $item['size'], 'modifyBy' => '', 'modifyDate' => $dateTime->format('d.m.Y'), 'modifyDateInt' => $dateTime->getTimestamp(), 'provider' => static::getCode());
         if (!$isFolder) {
             $reformatItems[$item['id']]['storage'] = '';
             $reformatItems[$item['id']]['ext'] = getFileExtension($item['name']);
         }
     }
     unset($item);
     return $reformatItems;
 }
示例#10
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");
     }
 }
示例#11
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");
     }
 }
示例#12
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");
     }
 }
示例#13
0
文件: index.php 项目: Hawkart/megatv
 /**
  * @return bool|string
  */
 protected function getArchive()
 {
     $client = new HttpClient();
     $fileName = pathinfo(self::ARCHIVE_URL, PATHINFO_BASENAME);
     if (!$client->download(self::ARCHIVE_URL, $_SERVER['DOCUMENT_ROOT'] . '/bitrix/tmp/' . $fileName)) {
         $this->errors = $client->getError();
         return false;
     } else {
         return $_SERVER['DOCUMENT_ROOT'] . '/bitrix/tmp/' . $fileName;
     }
 }
示例#14
0
 public function getMessages($uid)
 {
     if ($this->access_token === false) {
         return false;
     }
     $url = self::GRAPH_URL . '/' . $uid . '/apprequests?access_token=' . $this->access_token;
     $ob = new HttpClient();
     return $ob->get($url);
 }
示例#15
0
 protected function getSharedEmbedLink(FileData $fileData)
 {
     if (!$this->checkRequiredInputParams($fileData->toArray(), array('id'))) {
         return null;
     }
     $accessToken = $this->getAccessToken();
     $http = new HttpClient(array('socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1));
     $accessToken = urlencode($accessToken);
     if ($http->get("https://apis.live.net/v5.0/{$fileData->getId()}/embed?access_token={$accessToken}") === false) {
         $errorString = implode('; ', array_keys($http->getError()));
         $this->errorCollection->add(array(new Error($errorString, self::ERROR_SHARED_EMBED_LINK)));
         return null;
     }
     if (!$this->checkHttpResponse($http)) {
         return null;
     }
     $finalOutput = Json::decode($http->getResult());
     if ($finalOutput === null) {
         $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON)));
         return null;
     }
     if (!preg_match('%src="(.*)"%iuU', $finalOutput['embed_html'], $m)) {
         $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_ONE_DRIVE_HANDLER_ERROR_COULD_NOT_FIND_EMBED_LINK'), self::ERROR_COULD_NOT_FIND_EMBED_LINK)));
         return null;
     }
     return $m[1];
 }
示例#16
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;
 }
示例#17
0
 public function GetCurrentUser()
 {
     if ($this->access_token === false) {
         return false;
     }
     $h = new HttpClient();
     $h->setHeader("Authorization", "Bearer " . $this->access_token);
     $result = $h->get(static::ACCOUNT_URL);
     $result = Json::decode($result);
     if (is_array($result)) {
         $result["access_token"] = $this->access_token;
     }
     return $result;
 }
示例#18
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;
 }
示例#19
0
<?php

if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
    die;
}
use Bitrix\Main\Web\HttpClient;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\IO\Path;
Loc::loadLanguageFile(Path::combine(__DIR__, "statuses.php"));
$orderID = strlen(CSalePaySystemAction::GetParamValue("ORDER_ID")) > 0 ? CSalePaySystemAction::GetParamValue("ORDER_ID") : $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["ID"];
$login = CSalePaySystemAction::GetParamValue("API_LOGIN");
$password = CSalePaySystemAction::GetParamValue("API_PASSWORD");
$shopId = CSalePaySystemAction::GetParamValue("SHOP_ID");
$changePayStatus = CSalePaySystemAction::GetParamValue("CHANGE_STATUS_PAY") == "Y";
$statusUrl = "https://w.qiwi.com/api/v2/prv/{prv_id}/bills/{bill_id}";
$request = new HttpClient();
$request->setAuthorization($login, $password);
$request->setHeader("Accept", "text/json");
$request->setCharset("utf-8");
$response = $request->get(str_replace(array("{prv_id}", "{bill_id}"), array($shopId, $orderID), $statusUrl));
if ($response === false) {
    return 1;
}
$response = (array) json_decode($response);
if (!$response || !isset($response['response'])) {
    return 1;
}
$response = (array) $response['response'];
if ((int) $response['result_code']) {
    CSaleOrder::Update($orderID, array("PS_STATUS" => "N", "PS_STATUS_CODE" => $response['result_code'], "PS_STATUS_MESSAGE" => Loc::getMessage("SALE_QWH_ERROR_CODE_" . $response['result_code']), "PS_STATUS_DESCRIPTION" => isset($response['description']) ? $response['description'] : "", "PS_RESPONSE_DATE" => \Bitrix\Main\Type\DateTime::createFromTimestamp(time())));
} elseif (isset($response['bill'])) {
示例#20
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);
 }
示例#21
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);
 }
示例#22
0
 /**
  * Lists folder contents
  * @param $path
  * @param $folderId
  * @return mixed
  */
 public function listFolder($path, $folderId)
 {
     if ($path === '/') {
         $folderId = '';
     } else {
         $folderId = $this->getForApiDecodedId($folderId);
     }
     $http = new HttpClient(array('socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1));
     $http->setHeader('Content-Type', 'application/json; charset=UTF-8');
     $http->setHeader('Authorization', "Bearer {$this->getAccessToken()}");
     if ($http->get(self::API_URL . "/metadata/auto/{$folderId}") === false) {
         $errorString = implode('; ', array_keys($http->getError()));
         $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_LIST_FOLDER)));
         return null;
     }
     if (!$this->checkHttpResponse($http)) {
         return null;
     }
     $items = Json::decode($http->getResult());
     if ($items === null) {
         $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON)));
         return null;
     }
     if (!isset($items['contents'])) {
         $this->errorCollection->add(array(new Error('Could not find items in response', self::ERROR_HTTP_LIST_FOLDER)));
         return null;
     }
     $reformatItems = array();
     foreach ($items['contents'] as $item) {
         $isFolder = (bool) $item['is_dir'];
         $dateTime = \DateTime::createFromFormat('D, d M Y H:i:s T', $item['modified']);
         $pseudoId = base64_encode($item['path']);
         $reformatItems[$pseudoId] = array('id' => $pseudoId, 'name' => bx_basename($item['path']), 'type' => $isFolder ? 'folder' : 'file', 'size' => $isFolder ? '' : \CFile::formatSize($item['bytes']), 'sizeInt' => $isFolder ? '' : $item['bytes'], 'modifyBy' => '', 'modifyDate' => $dateTime->format('d.m.Y'), 'modifyDateInt' => $dateTime->getTimestamp(), 'provider' => static::getCode());
         if (!$isFolder) {
             $reformatItems[$pseudoId]['storage'] = '';
             $reformatItems[$pseudoId]['ext'] = getFileExtension($reformatItems[$pseudoId]['name']);
         }
     }
     unset($item);
     return $reformatItems;
 }
示例#23
0
 /**
  * @param string $url Image's URL.
  * @return integer Saved file identifier
  */
 protected static function saveImage($url)
 {
     $fileId = false;
     $file = new \CFile();
     $httpClient = new HttpClient();
     $httpClient->setTimeout(5);
     $httpClient->setStreamTimeout(5);
     $urlComponents = parse_url($url);
     if ($urlComponents && strlen($urlComponents["path"]) > 0) {
         $tempPath = $file->GetTempName('', bx_basename($urlComponents["path"]));
     } else {
         $tempPath = $file->GetTempName('', bx_basename($url));
     }
     $httpClient->download($url, $tempPath);
     $fileName = $httpClient->getHeaders()->getFilename();
     $localFile = \CFile::MakeFileArray($tempPath);
     if (is_array($localFile)) {
         if (strlen($fileName) > 0) {
             $localFile['name'] = $fileName;
         }
         if (\CFile::CheckImageFile($localFile, 0, 0, 0, array("IMAGE")) === null) {
             $fileId = $file->SaveFile($localFile, 'urlpreview', true);
         }
     }
     return $fileId === false ? null : $fileId;
 }
示例#24
0
     $result['MESSAGE'] = Loc::getMessage('BX_CURRENCY_GET_RATE_ERR_CURRENCY');
 } else {
     $url = '';
     switch ($baseCurrency) {
         case 'UAH':
             $url = 'http://bank.gov.ua/NBUStatService/v1/statdirectory?exchange&date=' . $DB->FormatDate($date, CLang::GetDateFormat('SHORT', LANGUAGE_ID), 'YMD');
             break;
         case 'BYR':
             $url = 'http://www.nbrb.by//Services/XmlExRates.aspx?ondate=' . $DB->FormatDate($date, CLang::GetDateFormat('SHORT', LANGUAGE_ID), 'Y-M-D');
             break;
         case 'RUB':
         case 'RUR':
             $url = 'http://www.cbr.ru/scripts/XML_daily.asp?date_req=' . $DB->FormatDate($date, CLang::GetDateFormat('SHORT', LANGUAGE_ID), 'D.M.Y');
             break;
     }
     $http = new HttpClient();
     $data = $http->get($url);
     $charset = 'windows-1251';
     $matches = array();
     if (preg_match("/<" . "\\?XML[^>]{1,}encoding=[\"']([^>\"']{1,})[\"'][^>]{0,}\\?" . ">/i", $data, $matches)) {
         $charset = trim($matches[1]);
     }
     $data = preg_replace("#<!DOCTYPE[^>]+?>#i", '', $data);
     $data = preg_replace("#<" . "\\?XML[^>]+?\\?" . ">#i", '', $data);
     $data = $APPLICATION->ConvertCharset($data, $charset, SITE_CHARSET);
     $objXML = new CDataXML();
     $res = $objXML->LoadString($data);
     if ($res !== false) {
         $data = $objXML->GetArray();
     } else {
         $data = false;
示例#25
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;
     }
 }