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; }
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'); }
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); }
/** * 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; }
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); }
/** * 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; }
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]; }
/** * @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; } }