Пример #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']);
         }
     }
 }
Пример #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
 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;
 }
Пример #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
 /**
  * Gets a file's metadata by ID
  * @param FileData $fileData
  * @return array|null
  */
 private function getFileMetadataInternal(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));
     $http->setHeader('Content-Type', 'application/json; charset=UTF-8');
     $http->setHeader('Authorization', "Bearer {$accessToken}");
     if ($http->get(self::API_URL_V2 . '/files/' . $fileData->getId()) === 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;
     }
     $file = Json::decode($http->getResult());
     if ($file === null) {
         $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON)));
         return null;
     }
     return $file;
 }
Пример #7
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;
 }
Пример #8
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");
     }
 }
Пример #9
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];
 }
Пример #10
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;
 }
Пример #11
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;
 }
Пример #12
0
 public function getNewAccessToken($refreshToken = false, $userId = 0, $save = false, $scope = array())
 {
     if ($this->appID == false || $this->appSecret == false) {
         return false;
     }
     if ($refreshToken == false) {
         $refreshToken = $this->refresh_token;
     }
     if ($scope != null) {
         $this->addScope($scope);
     }
     $http = new HttpClient(array('socketTimeout' => $this->httpTimeout));
     require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/update_client.php";
     $url = self::URL . self::TOKEN_URL . '?' . http_build_query(array('client_id' => $this->appID, 'client_secret' => $this->appSecret, 'refresh_token' => $refreshToken, 'scope' => implode(',', $this->getScope()), 'grant_type' => 'refresh_token', 'key' => md5(\CUpdateClient::GetLicenseKey())));
     $result = $http->get($url);
     if ($result) {
         try {
             $this->authResult = Json::decode($result);
         } catch (\Bitrix\Main\ArgumentException $e) {
             $result = "";
         }
     }
     if ($result) {
         if (isset($this->authResult["access_token"]) && $this->authResult["access_token"] != '') {
             $this->access_token = $this->authResult["access_token"];
             $this->accessTokenExpires = time() + $this->authResult["expires_in"];
             $this->refresh_token = $this->authResult["refresh_token"];
             return true;
         }
     }
     Service::getEngine()->clearAuthSettings();
     return false;
 }
Пример #13
0
}
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'])) {
    $bill = (array) $response['bill'];
    if ($order = CSaleOrder::getByID($bill['bill_id'])) {
        $paidInfo = array("PS_STATUS" => $bill['status'] == "paid" ? "Y" : "N", "PS_STATUS_CODE" => substr($bill['status'], 0, 10), "PS_STATUS_MESSAGE" => Loc::getMessage("SALE_QWH_STATUS_MESSAGE_" . strtoupper($bill['status'])), "PS_RESPONSE_DATE" => \Bitrix\Main\Type\DateTime::createFromTimestamp(time()), "PS_SUM" => (double) $bill['amount'], "PS_CURRENCY" => $bill['ccy'], 'PS_STATUS_DESCRIPTION' => '');
        foreach ($bill as $key => $value) {
Пример #14
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;
 }
Пример #15
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;
     }
 }
Пример #16
0
 } 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;
     }
Пример #17
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);
 }