Ejemplo n.º 1
0
 public function getData()
 {
     $xml_str = file_get_contents($this->file);
     $xml = new \CDataXML();
     $xml->LoadString($xml_str);
     $arXml = $xml->GetArray();
     unset($xml_str);
     return $this->toTmp($arXml);
 }
Ejemplo n.º 2
0
 function GetBoardFromSite($queryParameters)
 {
     global $APPLICATION;
     $result = array();
     $ob = new CHTTP();
     $ob->http_timeout = 60;
     $ob->Query("GET", "old.vnukovo.ru", 80, "/rus/for-passengers/board1/data.wbp?" . $queryParameters . '&ts=' . mktime(), false, "", "N");
     $result["ERROR"]["CODE"] = $ob->errno;
     $result["ERROR"]["MESSAGE"] = $ob->errstr;
     if (!intval($result["ERROR"]["CODE"])) {
         $res = $APPLICATION->ConvertCharset($ob->result, "UTF-8", SITE_CHARSET);
         //trace($res);
         $xml = new CDataXML();
         if ($xml->LoadString($res) && ($node = $xml->SelectNodes("/responce/rows"))) {
             $rows = $node->elementsByName("row");
             $akNames = array();
             $akCodes = array();
             $departures = array();
             $arrivals = array();
             $terminals = array();
             foreach ($rows as $row) {
                 $cells = $row->elementsByName("cell");
                 // Определяем код авиакомпании и номер рейса
                 preg_match_all("/([A-Za-zА-Яа-я0-9]{2})[\\s]*([0-9]+)/", $cells[0]->content, $flightNumber, PREG_PATTERN_ORDER);
                 $result["FLIGHTS"][] = array("FLIGHT" => array("AK_CODE" => $flightNumber[1][0], "NUMBER" => $flightNumber[2][0]), "AK_NAME" => htmlspecialcharsEx($cells[1]->content), "DEPARTURE" => htmlspecialcharsEx($cells[2]->content), "ARRIVAL" => htmlspecialcharsEx($cells[3]->content), "STATUS" => CAirportBoard::GetStatusInfo($cells[4]->content), "TIME" => array("PLANNED" => CAirportBoard::GetDateTimeArray($cells[5]->content), "ESTIMATED" => CAirportBoard::GetDateTimeArray($cells[6]->content), "ACTUAL" => CAirportBoard::GetDateTimeArray($cells[7]->content)), "TERMINAL" => htmlspecialcharsEx($cells[8]->content));
                 // Формируем список уникальных авиакомпаний, терминалов и пунктов вылета и прилета для фильтра
                 if (!in_array(htmlspecialcharsEx($cells[1]->content), $akNames)) {
                     $akNames[] = htmlspecialcharsEx($cells[1]->content);
                 }
                 if (!in_array($flightNumber[1][0], $akCodes)) {
                     $akCodes[] = $flightNumber[1][0];
                 }
                 if (!in_array(htmlspecialcharsEx($cells[2]->content), $departures)) {
                     $departures[] = htmlspecialcharsEx($cells[2]->content);
                 }
                 if (!in_array(htmlspecialcharsEx($cells[3]->content), $arrivals)) {
                     $arrivals[] = htmlspecialcharsEx($cells[3]->content);
                 }
                 if (!in_array(htmlspecialcharsEx($cells[8]->content), $terminals)) {
                     $terminals[] = htmlspecialcharsEx($cells[8]->content);
                 }
             }
             sort($akNames);
             sort($akCodes);
             sort($departures);
             sort($arrivals);
             sort($terminals);
             $result["AK_NAMES"] = $akNames;
             $result["AK_CODES"] = $akCodes;
             $result["DEPARTURES"] = $departures;
             $result["ARRIVALS"] = $arrivals;
             $result["TERMINALS"] = $terminals;
         }
     }
     return $result;
 }
Ejemplo n.º 3
0
 /**
  * Returns action response XML
  *
  * @param string $action
  * @return CDataXML
  * @throws CBitrixCloudException
  */
 protected function action($action)
 {
     /* @var CMain $APPLICATION */
     global $APPLICATION;
     $url = $this->getActionURL(array("action" => $action, "debug" => $this->debug ? "y" : "n"));
     $this->server = new CHTTP();
     if ($this->timeout > 0) {
         $this->server->http_timeout = $this->timeout;
     }
     $strXML = $this->server->Get($url);
     if ($strXML === false) {
         $e = $APPLICATION->GetException();
         if (is_object($e)) {
             throw new CBitrixCloudException($e->GetString(), "");
         } else {
             throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_SERVER", array("#STATUS#" => "-1")), "");
         }
     }
     if ($this->server->status != 200) {
         throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_SERVER", array("#STATUS#" => (string) $this->server->status)), "");
     }
     $obXML = new CDataXML();
     if (!$obXML->LoadString($strXML)) {
         throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_XML_PARSE", array("#CODE#" => "1")), "");
     }
     $node = $obXML->SelectNodes("/error/code");
     if (is_object($node)) {
         $error_code = $node->textContent();
         $message_id = "BCL_CDN_WS_" . $error_code;
         /*
         GetMessage("BCL_CDN_WS_LICENSE_EXPIRE");
         GetMessage("BCL_CDN_WS_LICENSE_NOT_FOUND");
         GetMessage("BCL_CDN_WS_QUOTA_EXCEEDED");
         GetMessage("BCL_CDN_WS_CMS_LICENSE_NOT_FOUND");
         GetMessage("BCL_CDN_WS_DOMAIN_NOT_REACHABLE");
         GetMessage("BCL_CDN_WS_LICENSE_DEMO");
         GetMessage("BCL_CDN_WS_LICENSE_NOT_ACTIVE");
         GetMessage("BCL_CDN_WS_NOT_POWERED_BY_BITRIX_CMS");
         GetMessage("BCL_CDN_WS_WRONG_DOMAIN_SPECIFIED");
         */
         $debug_content = "";
         $node = $obXML->SelectNodes("/error/debug");
         if (is_object($node)) {
             $debug_content = $node->textContent();
         }
         if (HasMessage($message_id)) {
             throw new CBitrixCloudException(GetMessage($message_id), $error_code, $debug_content);
         } else {
             throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_SERVER", array("#STATUS#" => $error_code)), $error_code, $debug_content);
         }
     }
     return $obXML;
 }
Ejemplo n.º 4
0
 function Request($server, $page, $port, $params, $uri = false)
 {
     if ($uri && strlen($uri) > 0) {
         $strURI = $uri;
     } else {
         $strURI = "http://" . $server . (strlen($port) > 0 && intval($port) > 0 ? ":" . intval($port) : "") . (strlen($page) ? $page : "/") . (strlen($params) > 0 ? "?" . $params : "");
     }
     $http = new \Bitrix\Main\Web\HttpClient(array("version" => "1.0", "socketTimeout" => 30, "streamTimeout" => 30, "redirect" => true, "redirectMax" => 5));
     $strData = $http->get($strURI);
     $errors = $http->getError();
     $arRSSResult = array();
     if (!$strData && !empty($errors)) {
         $strError = "";
         foreach ($errors as $errorCode => $errMes) {
             $strError .= $errorCode . ": " . $errMes;
         }
         \CEventLog::Add(array("SEVERITY" => "ERROR", "AUDIT_TYPE_ID" => "XDIMPORT_HTTP", "MODULE_ID" => "xdimport", "ITEM_ID" => "RSS_REQUEST", "DESCRIPTION" => $strError));
     }
     if ($strData) {
         $rss_charset = "windows-1251";
         if (preg_match("/<" . "\\?XML[^>]{1,}encoding=[\"']([^>\"']{1,})[\"'][^>]{0,}\\?" . ">/i", $strData, $matches)) {
             $rss_charset = Trim($matches[1]);
         }
         $strData = preg_replace("/<" . "\\?XML.*?\\?" . ">/i", "", $strData);
         $strData = $GLOBALS["APPLICATION"]->ConvertCharset($strData, $rss_charset, SITE_CHARSET);
     }
     if (strlen($strData) > 0) {
         require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
         $objXML = new CDataXML();
         $res = $objXML->LoadString($strData);
         if ($res !== false) {
             $ar = $objXML->GetArray();
             if (is_array($ar) && isset($ar["rss"]) && is_array($ar["rss"]) && isset($ar["rss"]["#"]) && is_array($ar["rss"]["#"]) && isset($ar["rss"]["#"]["channel"]) && is_array($ar["rss"]["#"]["channel"]) && isset($ar["rss"]["#"]["channel"][0]) && is_array($ar["rss"]["#"]["channel"][0]) && isset($ar["rss"]["#"]["channel"][0]["#"])) {
                 $arRSSResult = $ar["rss"]["#"]["channel"][0]["#"];
             } else {
                 $arRSSResult = array();
             }
             $arRSSResult["rss_charset"] = strtolower(SITE_CHARSET);
         }
     }
     if (is_array($arRSSResult) && !empty($arRSSResult)) {
         $arRSSResult = CXDILFSchemeRSS::FormatArray($arRSSResult);
         if (!empty($arRSSResult) && array_key_exists("item", $arRSSResult) && is_array($arRSSResult["item"]) && !empty($arRSSResult["item"])) {
             $arRSSResult["item"] = array_reverse($arRSSResult["item"]);
         }
     }
     return $arRSSResult;
 }
Ejemplo n.º 5
0
 function AddFlightsToResult($html, $result, $terminal)
 {
     $res = '<table>' . $html . '</table>';
     $res = str_replace("&nbsp;", " ", $res);
     $res = str_replace("<br>", " ", $res);
     $res = preg_replace("/<!--.*-->/Uis", "", $res);
     $res = preg_replace("/<colgroup>.*<\\/colgroup>/Uis", "", $res);
     $res = preg_replace("/<param[^>]*>/Uis", "", $res);
     $res = preg_replace("/<a[^>]*>[^<]+<\\/a>/Uis", "", $res);
     //trace($res);
     $xml = new CDataXML();
     if ($xml->LoadString($res)) {
         $node = $xml->SelectNodes("/table");
         $rows = $node->elementsByName("tr");
         $i = 0;
         foreach ($rows as $row) {
             //trace($row->getAttribute("class"));
             if (!strstr($row->getAttribute("class"), "onlineDetailTr")) {
                 $cells = $row->elementsByName("td");
                 if (count($cells) && preg_match("/([A-Za-zА-Яа-я0-9]{2})\\s*([0-9]+)\\s*/", $cells[0]->content)) {
                     // Определяем код авиакомпании и номер рейса
                     preg_match_all("/([A-Za-zА-Яа-я0-9]{2})\\s*([0-9]+)\\s*/", $cells[0]->content, $flightNumber, PREG_PATTERN_ORDER);
                     $result["FLIGHTS"][$i] = array("FLIGHT" => array("AK_CODE" => $flightNumber[1][0], "NUMBER" => $flightNumber[2][0]), "AK_NAME" => htmlspecialcharsEx($cells[5]->content), "DEPARTURE" => htmlspecialcharsEx($cells[1]->content), "ARRIVAL" => htmlspecialcharsEx($cells[1]->content), "STATUS" => CAirportBoard::GetStatusInfo($cells[4]->content), "TIME" => array("PLANNED" => CAirportBoard::GetDateTimeArray($cells[2]->content), "ESTIMATED" => "", "ACTUAL" => CAirportBoard::GetDateTimeArray($cells[3]->content)), "TERMINAL" => $terminal);
                     // Формируем список уникальных терминалов и пунктов вылета и прилета для фильтра
                     if (!in_array($flightNumber[1][0], $result["AK_CODES"])) {
                         $result["AK_CODES"][] = $flightNumber[1][0];
                     }
                     if (!in_array($result["FLIGHTS"][$i]["AK_NAME"], $result["AK_NAMES"]) && strlen($result["FLIGHTS"][$i]["AK_NAME"])) {
                         $result["AK_NAMES"][] = $result["FLIGHTS"][$i]["AK_NAME"];
                     }
                     if (!in_array($result["FLIGHTS"][$i]["DEPARTURE"], $result["DEPARTURES"])) {
                         $result["DEPARTURES"][] = $result["FLIGHTS"][$i]["DEPARTURE"];
                     }
                     if (!in_array($result["FLIGHTS"][$i]["ARRIVAL"], $result["ARRIVALS"])) {
                         $result["ARRIVALS"][] = $result["FLIGHTS"][$i]["ARRIVAL"];
                     }
                     if (!in_array($result["FLIGHTS"][$i]["TERMINAL"], $result["TERMINALS"])) {
                         $result["TERMINALS"][] = $result["FLIGHTS"][$i]["TERMINAL"];
                     }
                     $i++;
                 }
             }
         }
     }
     unset($html, $xml, $res);
     return $result;
 }
Ejemplo n.º 6
0
 /**
  * Returns action response XML
  *
  * @param string $action
  * @return CDataXML
  *
  */
 protected function action($action)
 {
     global $APPLICATION;
     $url = $this->getActionURL(array("action" => $action));
     $server = new CHTTP();
     $strXML = $server->Get($url);
     if ($strXML === false) {
         $e = $APPLICATION->GetException();
         if (is_object($e)) {
             throw new CBitrixCloudException($e->GetString(), "");
         } else {
             throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_SERVER", array("#STATUS#" => "-1")), "");
         }
     }
     if ($server->status != 200) {
         throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_SERVER", array("#STATUS#" => (string) $server->status)), "");
     }
     $obXML = new CDataXML();
     if (!$obXML->LoadString($strXML)) {
         throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_XML_PARSE", array("#CODE#" => "1")), "");
     }
     $node = $obXML->SelectNodes("/error/code");
     if (is_object($node)) {
         $error_code = $node->textContent();
         $message_id = "BCL_CDN_WS_" . $error_code;
         /*
         GetMessage("BCL_CDN_WS_LICENSE_EXPIRE");
         GetMessage("BCL_CDN_WS_LICENSE_NOT_FOUND");
         GetMessage("BCL_CDN_WS_QUOTA_EXCEEDED");
         */
         if (HasMessage($message_id)) {
             throw new CBitrixCloudException(GetMessage($message_id), $error_code);
         } else {
             throw new CBitrixCloudException(GetMessage("BCL_CDN_WS_SERVER", array("#STATUS#" => $error_code)), $error_code);
         }
     }
     return $obXML;
 }
Ejemplo n.º 7
0
	function GetNewsEx($SITE, $PORT, $PATH, $QUERY_STR, $bOutChannel = False)
	{
		global $APPLICATION;

		$cacheKey = md5($SITE.$PORT.$PATH.$QUERY_STR);

		$bValid = False;
		$bUpdate = False;
		if ($db_res_arr = CIBlockRSS::GetCache($cacheKey))
		{
			$bUpdate = True;
			if (strlen($db_res_arr["CACHE"])>0)
			{
				if ($db_res_arr["VALID"]=="Y")
				{
					$bValid = True;
					$text = $db_res_arr["CACHE"];
				}
			}
		}

		if (!$bValid)
		{
			$FP = fsockopen($SITE, $PORT, $errno, $errstr, 120);

			if ($FP)
			{
				$strVars = $QUERY_STR;
				$strRequest = "GET ".$PATH.(strlen($strVars) > 0? "?".$strVars: "")." HTTP/1.0\r\n";
				$strRequest.= "User-Agent: BitrixSMRSS\r\n";
				$strRequest.= "Accept: */*\r\n";
				$strRequest.= "Host: $SITE\r\n";
				$strRequest.= "Accept-Language: en\r\n";
				$strRequest.= "\r\n";
				fputs($FP, $strRequest);

				$headers = "";
				while(!feof($FP))
				{
					$line = fgets($FP, 4096);
					if($line == "\r\n")
						break;
					$headers .= $line;
				}

				$text = "";
				while(!feof($FP))
					$text .= fread($FP, 4096);

				$rss_charset = "windows-1251";
				if (preg_match("/<"."\?XML[^>]{1,}encoding=[\"']([^>\"']{1,})[\"'][^>]{0,}\?".">/i", $text, $matches))
				{
					$rss_charset = Trim($matches[1]);
				}
				elseif($headers)
				{
					if(preg_match("#^Content-Type:.*?charset=([a-zA-Z0-9-]+)#m", $headers, $match))
						$rss_charset = $match[1];
				}

				$text = preg_replace("/<!DOCTYPE.*?>/i", "", $text);
				$text = preg_replace("/<"."\\?XML.*?\\?".">/i", "", $text);
				$text = $APPLICATION->ConvertCharset($text, $rss_charset, SITE_CHARSET);

				fclose($FP);
			}
			else
			{
				$text = "";
			}
		}

		if (strlen($text) > 0)
		{
			require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/classes/general/xml.php");
			$objXML = new CDataXML();
			$res = $objXML->LoadString($text);
			if($res !== false)
			{
				$ar = $objXML->GetArray();
				//$ar = xmlize_rss($text1);

				if (!$bOutChannel)
				{
					$arRes = $ar["rss"]["#"]["channel"][0]["#"];
				}
				else
				{
					$arRes = $ar["rss"]["#"];
				}

				$arRes["rss_charset"] = strtolower(SITE_CHARSET);

				if (!$bValid)
				{
					$ttl = (strlen($arRes["ttl"][0]["#"]) > 0)? IntVal($arRes["ttl"][0]["#"]): 60;
					CIBlockRSS::UpdateCache($cacheKey, $text, array("minutes" => $ttl), $bUpdate);
				}
			}
			return $arRes;
		}
		else
		{
			return array();
		}
	}
 private function ParseOrderData($orderData, &$modificationLabel, &$arErrors)
 {
     if (empty($orderData)) {
         $arErrors[] = array("PD1", GetMessage("CRM_EXT_SALE_IMPORT_EMPTY_ANSW"));
         return null;
     }
     if (substr(ltrim($orderData), 0, strlen('<?xml')) != '<?xml') {
         $orderDataTmp = @gzuncompress($orderData);
         if (substr(ltrim($orderDataTmp), 0, strlen('<?xml')) != '<?xml') {
             if (strpos($orderDataTmp, "You haven't rights for exchange") !== false) {
                 $arErrors[] = array("PD2", GetMessage("CRM_EXT_SALE_IMPORT_UNKNOWN_ANSW_PERMS"));
             } elseif (strpos($orderDataTmp, "failure") !== false) {
                 $arErrors[] = array("PD2", GetMessage("CRM_EXT_SALE_IMPORT_UNKNOWN_ANSW_F"));
                 $arErrors[] = array("PD2", preg_replace("/\\s*failure\n/", "", $orderDataTmp));
             } elseif (strpos($orderData, "Authorization") !== false || strpos($orderData, "Access denied") !== false) {
                 $arErrors[] = array("PD2", GetMessage("CRM_EXT_SALE_IMPORT_UNKNOWN_ANSW_PERMS1"));
             } else {
                 $arErrors[] = array("PD2", GetMessage("CRM_EXT_SALE_IMPORT_UNKNOWN_ANSW") . substr($orderData, 0, 100));
             }
             return null;
         }
         $orderData = $orderDataTmp;
         unset($orderDataTmp);
     }
     $charset = "";
     if (preg_match("/^<" . "\\?xml[^>]+?encoding=[\"']([^>\"']+)[\"'][^>]*\\?" . ">/i", $orderData, $matches)) {
         $charset = trim($matches[1]);
     }
     if (!empty($charset) && strtoupper($charset) != strtoupper(SITE_CHARSET)) {
         $orderData = CharsetConverter::ConvertCharset($orderData, $charset, SITE_CHARSET);
     }
     $objXML = new CDataXML();
     if ($objXML->LoadString($orderData)) {
         $arOrderData = $objXML->GetArray();
     } else {
         $arErrors[] = array("XL1", GetMessage("CRM_EXT_SALE_IMPORT_ERROR_XML"));
         return null;
     }
     $arSettings = array();
     foreach ($arOrderData["CommerceInformation"]["@"] as $key => $value) {
         $arSettings[$key] = array();
         $ar1 = explode(";", $value);
         foreach ($ar1 as $v1) {
             $ar2 = explode("=", $v1);
             if (count($ar2) == 2) {
                 $arSettings[$key][trim($ar2[0])] = $ar2[1];
             }
         }
         if (count($arSettings[$key]) <= 0) {
             $arSettings[$key] = $value;
         }
     }
     if (!isset($arSettings["SumFormat"]["CRD"])) {
         $arSettings["SumFormat"]["CRD"] = '.';
     }
     if (!isset($arSettings["QuantityFormat"]["CRD"])) {
         $arSettings["QuantityFormat"]["CRD"] = '.';
     }
     if (!isset($arSettings["DateFormat"]["DF"])) {
         $arSettings["DateFormat"]["DF"] = 'yyyy-MM-dd';
     }
     $arSettings["DateFormat"]["DF"] = strtoupper($arSettings["DateFormat"]["DF"]);
     if (!isset($arSettings["TimeFormat"]["DF"])) {
         $arSettings["TimeFormat"]["DF"] = 'HH:MM:SS';
     }
     $arSettings["TimeFormat"]["DF"] = str_replace("MM", "MI", $arSettings["TimeFormat"]["DF"]);
     $arOrders = array();
     if (is_array($arOrderData["CommerceInformation"]["#"]) && is_array($arOrderData["CommerceInformation"]["#"]["Document"])) {
         foreach ($arOrderData["CommerceInformation"]["#"]["Document"] as $arDocument) {
             if ($arDocument["#"]["BusinessTransaction"][0]["#"] == "ItemOrder") {
                 $v = $this->ParseOrderDataOrder($arDocument, $arSettings);
                 if (is_array($v)) {
                     $arOrders[] = $v;
                     if (isset($v["DATE_UPDATE"])) {
                         $modificationLabelTmp = MakeTimeStamp($v["DATE_UPDATE"]);
                         if ($modificationLabelTmp > $modificationLabel) {
                             $modificationLabel = $modificationLabelTmp;
                         }
                     }
                 }
             }
         }
     }
     return $arOrders;
 }
Ejemplo n.º 9
0
 function SendRequest($access_key, $secret_key, $verb, $bucket, $file_name = '/', $params = '')
 {
     global $APPLICATION;
     $this->status = 0;
     $RequestMethod = $verb;
     $RequestHost = "sts.amazonaws.com";
     $RequestURI = "/";
     $RequestParams = "";
     $params['SignatureVersion'] = 2;
     $params['SignatureMethod'] = 'HmacSHA1';
     $params['AWSAccessKeyId'] = $access_key;
     $params['Timestamp'] = gmdate('Y-m-d') . 'T' . gmdate('H:i:s');
     //.preg_replace("/(\d\d)\$/", ":\\1", date("O"));
     $params['Version'] = '2011-06-15';
     ksort($params);
     foreach ($params as $name => $value) {
         if ($RequestParams != '') {
             $RequestParams .= '&';
         }
         $RequestParams .= urlencode($name) . "=" . urlencode($value);
     }
     $StringToSign = "{$RequestMethod}\n" . "{$RequestHost}\n" . "{$RequestURI}\n" . "{$RequestParams}";
     $Signature = urlencode(base64_encode($this->hmacsha1($StringToSign, $secret_key)));
     $obRequest = new CHTTP();
     $obRequest->Query($RequestMethod, $RequestHost, 443, $RequestURI . "?{$RequestParams}&Signature={$Signature}", false, 'ssl://');
     $this->status = $obRequest->status;
     $this->headers = $obRequest->headers;
     $this->errno = $obRequest->errno;
     $this->errstr = $obRequest->errstr;
     $this->result = $obRequest->result;
     if ($obRequest->status == 200) {
         if ($obRequest->result) {
             $obXML = new CDataXML();
             $text = preg_replace("/<" . "\\?XML.*?\\?" . ">/i", "", $obRequest->result);
             if ($obXML->LoadString($text)) {
                 $arXML = $obXML->GetArray();
                 if (is_array($arXML)) {
                     return $arXML;
                 }
             }
             //XML parse error
             $APPLICATION->ThrowException(GetMessage('CLO_SECSERV_S3_XML_PARSE_ERROR', array('#errno#' => 1)));
             return false;
         } else {
             //Empty success result
             return array();
         }
     } elseif ($obRequest->status > 0) {
         if ($obRequest->result) {
             $APPLICATION->ThrowException(GetMessage('CLO_SECSERV_S3_XML_ERROR', array('#errmsg#' => $obRequest->result)));
             return false;
         }
         $APPLICATION->ThrowException(GetMessage('CLO_SECSERV_S3_XML_PARSE_ERROR', array('#errno#' => 2)));
         return false;
     } else {
         $APPLICATION->ThrowException(GetMessage('CLO_SECSERV_S3_XML_PARSE_ERROR', array('#errno#' => 3)));
         return false;
     }
 }
Ejemplo n.º 10
0
     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;
 }
 switch ($baseCurrency) {
     case 'UAH':
         if (is_array($data) && count($data["exchange"]["#"]['currency']) > 0) {
             $currencyList = $data['exchange']['#']['currency'];
             foreach ($currencyList as &$currencyRate) {
                 if ($currencyRate['#']['cc'][0]['#'] == $currency) {
                     $result['STATUS'] = 'OK';
                     $result['RATE_CNT'] = 1;
                     $result['RATE'] = (double) str_replace(",", ".", $currencyRate['#']['rate'][0]['#']);
                     break;
Ejemplo n.º 11
0
	public function UpdateListItems($listName, $updates)
	{
		global $USER;

		$arStatusValues = array_flip($this->arStatusValues);
		$arPriorityValues = array_flip($this->arPriorityValues);

		if (!$listName_original = CIntranetUtils::checkGUID($listName))
			return new CSoapFault('Data error', 'Wrong GUID - '.$listName);

		$obResponse = new CXMLCreator('Results');

		$listName = ToUpper(CIntranetUtils::makeGUID($listName_original));
		$arSections = CCalendarSect::GetList(array('arFilter' => array('XML_ID' => $listName_original)));
		if (!$arSections || !is_array($arSections[0]))
			return new CSoapFault(
				'List not found',
				'List with '.$listName.' GUID not found'
			);
		$arSection = $arSections[0];

		$bGroup = $arSection['CAL_TYPE'] == 'group';
		$calType = $arSection['CAL_TYPE'];
		$ownerId = $arSection['OWNER_ID'];

		if ($bGroup)
		{
			CModule::IncludeModule('socialnetwork');
			$arGroupTmp = CSocNetGroup::GetByID($arSection['SOCNET_GROUP_ID']);
			if ($arGroupTmp["CLOSED"] == "Y")
				if (COption::GetOptionString("socialnetwork", "work_with_closed_groups", "N") != "Y")
					return new CSoapFault('Cannot modify archive group calendar', 'Cannot modify archive group calendar');
		}

		$obBatch = $updates->children[0];
		$atrONERROR = $obBatch->getAttribute('OnError');
		$atrDATEINUTC = $obBatch->getAttribute('DateInUtc');
		$atrPROPERTIES = $obBatch->getAttribute('Properties');

		$arChanges = $obBatch->children;

		$arResultIDs = array();
		$dateStart = ConvertTimeStamp(strtotime('-1 hour'), 'FULL');
		$arResponseRows = array();
		$arReplicationIDs = array();
		$userId = (is_object($USER) && $USER->GetID()) ? $USER->GetID() : 1;

		foreach ($arChanges as $obMethod)
		{
			$arData = array('_command' => $obMethod->getAttribute('Cmd'));

			foreach ($obMethod->children as $obField)
			{
				$name = $obField->getAttribute('Name');
				if ($name == 'MetaInfo')
					$name .= '_'.$obField->getAttribute('Property');

				$arData[$name] = $obField->content;
			}

			if ($arData['_command'] == 'Delete')
			{
				$obRes = new CXMLCreator('Result');
				$obRes->setAttribute('ID', $obMethod->getAttribute('ID').','.$arData['_command']);
				$obRes->setAttribute('List', $listName);
				$obRes->addChild($obNode = new CXMLCreator('ErrorCode'));

				$res = CCalendar::DeleteEvent($arData['ID']);
				if ($res === true)
					$obNode->setData('0x00000000');
				else
					$obNode->setData('0x81020014');

				/*
					0x00000000 - ok
					0x81020015 - data conflict
					0x81020014 - generic error such as invalid value for Field
					0x81020016 - item does not exist
				*/

				$obResponse->addChild($obRes);
			}
			elseif ($arData['_command'] == 'New' || $arData['_command'] == 'Update')
			{
				$q = ToLower($arData['Description']);
				if (($pos = strrpos($q, '</body>')) !== false) $arData['Description'] = substr($arData['Description'], 0, $pos);
				if (($pos = strpos($q, '<body>')) !== false) $arData['Description'] = substr($arData['Description'], $pos + 6);

				$arData['Description'] = str_replace('</DIV>', "\r\n</DIV>", $arData['Description']);
				$arData['Description'] = str_replace(array("&#10;", "&#13;"), "", $arData['Description']);
				$arData['Description'] = preg_replace("/<![^>]*>/", '', $arData['Description']);
				//$arData['Description'] = strip_tags($arData['Description']);
				$arData['Description'] = trim($arData['Description']);

				$arData['Location'] = trim($arData['Location']);

				if (isset($arData['EventDate']))
				{
					$arData['EventDate'] = $this->__makeTS($arData['EventDate']);
					$arData['EndDate'] = $this->__makeTS($arData['EndDate']) + ($arData['fAllDayEvent'] ? -86340 : 0);
					$TZBias = intval(date('Z', $arData['EventDate']));
				}

				$arData['EventType'] = intval($arData['EventType']);

				if ($arData['EventType'] == 2)
					$arData['EventType'] = 0;

				if ($arData['EventType'] > 2 /* || ($arData['EventType'] == 1 && !$arData['RecurrenceData'])*/)
					return new CSoapFault(
						'Unsupported event type',
						'Event type unsupported'
					);

				$arData['fRecurrence'] = intval($arData['fRecurrence']);
				$arData['RRULE'] = '';

				$id = $arData['_command'] == 'New' ? 0 : intVal($arData['ID']);
				if ($arData['RecurrenceData'])
				{
					//$xmlstr = $arData['XMLTZone'];
					//$arData['XMLTZone'] = new CDataXML();
					//$arData['XMLTZone']->LoadString($xmlstr);

					$xmlstr = $arData['RecurrenceData'];
					$obRecurData = new CDataXML();
					$obRecurData->LoadString($xmlstr);

/*
<recurrence>
		<rule>
			<firstDayOfWeek>mo</firstDayOfWeek>
			<repeat>
				<weekly mo='TRUE' tu='TRUE' th='TRUE' sa='TRUE' weekFrequency='1' />
			</repeat>
			<repeatForever>FALSE</repeatForever>
		</rule>
</recurrence>
<deleteExceptions>true</deleteExceptions>
*/

					$obRecurRule = $obRecurData->tree->children[0]->children[0];
					$obRecurRepeat = $obRecurRule->children[1];
					$obNode = $obRecurRepeat->children[0];

					$arData['RRULE'] = array();
					switch($obNode->name)
					{
						case 'daily':
							// hack. we have no "work days" daily recurence
							if ($obNode->getAttribute('weekday') == 'TRUE')
							{
								$arData['RRULE']['FREQ'] = 'WEEKLY';
								$arData['RRULE']['BYDAY'] = 'MO,TU,WE,TH,FR';
								$arData['RRULE']['INTERVAL'] = 1;
							}
							else
							{
								$arData['RRULE']['FREQ'] = 'DAILY';
								$arData['RRULE']['INTERVAL'] = $obNode->getAttribute('dayFrequency');
							}

							$time_end = strtotime(
								date(date('Y-m-d', $arData['EventDate']).' H:i:s', $arData['EndDate'])
							);

							$arData['DT_LENGTH'] = $time_end - $arData['EventDate'];
						break;

						case 'weekly':
							$arData['RRULE']['FREQ'] = 'WEEKLY';
							$arData['RRULE']['BYDAY'] = '';

							$arWeekDays = array('mo', 'tu', 'we', 'th', 'fr', 'sa', 'su');
							foreach ($arWeekDays as $day => $value)
							{
								if ($obNode->getAttribute($value))
									$arData['RRULE']['BYDAY'][] = strtoupper($value);
							}

							$arData['RRULE']['BYDAY'] = implode(',', $arData['RRULE']['BYDAY']);
							$arData['RRULE']['INTERVAL'] = $obNode->getAttribute('weekFrequency');

							$time_end = strtotime(date(date('Y-m-d', $arData['EventDate']).' H:i:s', $arData['EndDate']));

							$arData['DT_LENGTH'] = $time_end - $arData['EventDate'];
						break;

						case 'monthly':
							$arData['RRULE']['FREQ'] = 'MONTHLY';
							$arData['RRULE']['INTERVAL'] = $obNode->getAttribute('monthFrequency');
							$time_end = strtotime(date(date('Y-m', $arData['EventDate']).'-d H:i:s', $arData['EndDate']));

							$arData['DT_LENGTH'] = $time_end - $arData['EventDate'];
						break;

						case 'yearly':
							$arData['RRULE']['FREQ'] = 'YEARLY';
							$arData['RRULE']['INTERVAL'] = $obNode->getAttribute('yearFrequency');

							$time_end = strtotime(date(date('Y', $arData['EventDate']).'-m-d H:i:s', $arData['EndDate']));

							$arData['DT_LENGTH'] = $time_end - $arData['EventDate'];
						break;
					}

					if ($arData['DT_LENGTH'] == 0 && isset($arData['RRULE']['FREQ']))
						$arData['DT_LENGTH'] = 86400;

					$obWhile = $obRecurRule->children[2];
					if ($obWhile->name == 'repeatForever')
					{
						$arData['EndDate'] = MakeTimeStamp('');
					}
					elseif ($obWhile->name == 'windowEnd')
					{
						$arData['EndDate'] = $this->__makeTS($obWhile->textContent());
						$arData['RRULE']['UNTIL'] = ConvertTimeStamp($arData['EndDate'], 'FULL');
					}
				}
				elseif($arData['fRecurrence'] == -1 && $id > 0)
				{
					$arData['RRULE'] = -1;
				}

				if (isset($arData['EventDate']))
				{
					$skipTime = $arData['fAllDayEvent'] ? 'Y' : 'N';
					$TZBias = $arData['fAllDayEvent'] ? 0 : $TZBias;
					$arData['EventDate'] += $TZBias;
					$arData['EndDate'] += $TZBias;

//					$arData["DT_FROM"] = ConvertTimeStamp($arData['EventDate'], 'FULL');
//					$arData["DT_TO"] = ConvertTimeStamp($arData['EndDate'], 'FULL');
				}
				else
				{
					$arData["DT_FROM"] = -1;
					$arData["DT_TO"] = -1;
				}

				// fields
				$arFields = array(
					"ID" => $id,
					'CAL_TYPE' => $calType,
					'OWNER_ID' => $ownerId,
					'CREATED_BY' => $userId,
					'DT_FROM_TS' => $arData['EventDate'],
					'DT_TO_TS' => $arData['EndDate'],
					'DT_SKIP_TIME' => $skipTime,
//					"DT_FROM" => $arData["DT_FROM"],
//					"DT_TO" => $arData["DT_TO"],
					'NAME' => $arData['Title'],
					'DESCRIPTION' => CCalendar::ParseHTMLToBB($arData['Description']),
					'SECTIONS' => array($arSection['ID']),
					'ACCESSIBILITY' => $arStatusValues[$arData['MetaInfo_BusyStatus']],
					'IMPORTANCE' => $arPriorityValues[$arData['MetaInfo_Priority']],
					'RRULE' => $arData['RRULE'],
					'LOCATION' => CCalendar::UnParseTextLocation($arData['Location'])
				);

				if (isset($arData['DT_LENGTH']) && $arData['DT_LENGTH'] > 0)
					$arFields['DT_LENGTH'] = $arData['DT_LENGTH'];

				$EventID = CCalendar::SaveEvent(
					array(
						'arFields' => $arFields,
						'fromWebservice' => true
					)
				);

				if ($EventID)
				{
					// dirty hack
					$arReplicationIDs[$EventID] = $arData['MetaInfo_ReplicationID'];

					$arResponseRows[$EventID] = new CXMLCreator('Result');
					$arResponseRows[$EventID]->setAttribute('ID', $obMethod->getAttribute('ID').','.$arData['_command']);
					$arResponseRows[$EventID]->setAttribute('List', $listName);

					$arResponseRows[$EventID]->addChild($obNode = new CXMLCreator('ErrorCode'));
					$obNode->setData('0x00000000');
					//$arResponseRows[$EventID]->setAttribute('Version', 3);
				}
			}
		}

		$userId = (is_object($USER) && $USER->GetID()) ? $USER->GetID() : 1;
		$fetchMeetings = CCalendar::GetMeetingSection($userId) == $arSection['ID'];
		$arEvents = CCalendarEvent::GetList(
			array(
				'arFilter' => array(
					'CAL_TYPE' => $calType,
					'OWNER_ID' => $ownerId,
					'SECTION' => $arSection['ID'],
					//'INCLUDE_INVITINGS' => 'N'
				),
				'getUserfields' => false,
				'parseRecursion' => false,
				'fetchAttendees' => false,
				'fetchMeetings' => $fetchMeetings,
				'userId' => $userId
			)
		);

		foreach ($arEvents as $key => $event)
		{
			if ($arResponseRows[$event['ID']])
			{
				$obRow = $this->__getRow($event, $listName, $last_change = 0);
				$obRow->setAttribute('xmlns:z', "#RowsetSchema");
				if ($arReplicationIDs[$event['ID']])
					$obRow->setAttribute('MetaInfo_ReplicationID', $arReplicationIDs[$event['ID']]);

				$arResponseRows[$event['ID']]->addChild($obRow);
			}
			$obResponse->addChild($arResponseRows[$event['ID']]);
		}
		return array('UpdateListItemsResult' => $obResponse);
	}
Ejemplo n.º 12
0
    $arParams["PATH_TO_POST"] = htmlspecialchars($APPLICATION->GetCurPage() . "?" . $arParams["PAGE_VAR"] . "=post&" . $arParams["BLOG_VAR"] . "=#blog#&" . $arParams["POST_VAR"] . "=#post_id#");
}
if (function_exists("file_get_contents")) {
    $DATA = file_get_contents("php://input");
} elseif (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
    $DATA =& $GLOBALS["HTTP_RAW_POST_DATA"];
} else {
    $DATA = false;
}
if (toUpper(LANG_CHARSET) != "UTF-8") {
    $DATA = $APPLICATION->ConvertCharset($DATA, "UTF-8", LANG_CHARSET);
}
if (strlen($DATA) > 0) {
    require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
    $objXML = new CDataXML();
    $objXML->LoadString($DATA);
    $arResult = $objXML->GetArray();
    if (!empty($arResult)) {
        $params = $arResult["methodCall"]["#"]["params"][0]["#"]["param"];
        $arMethod = explode(".", $arResult["methodCall"]["#"]["methodName"][0]["#"]);
        $methodName = $arMethod[1];
        $methodClass = $arMethod[0];
        if (ToUpper($methodClass) == ToUpper("blogger") || ToUpper($methodClass) == ToUpper("metaWeblog")) {
            switch (ToUpper($methodName)) {
                case ToUpper("getUsersBlogs"):
                    $result = CBlogMetaWeblog::GetUsersBlogs($params, array("PATH_TO_BLOG" => $arParams["PATH_TO_BLOG"]));
                    break;
                case ToUpper("getCategories"):
                    $result = CBlogMetaWeblog::GetCategories($params);
                    break;
                case ToUpper("getRecentPosts"):
Ejemplo n.º 13
0
 /**
  * @param array[string]string $arSettings
  * @param string $verb
  * @param string $bucket
  * @param string $file_name
  * @param string $params
  * @param string $content
  * @param array[string]string $additional_headers
  * @return mixed
  */
 public function SendRequest($arSettings, $verb, $bucket, $file_name = '/', $params = '', $content = '', $additional_headers = array())
 {
     global $APPLICATION;
     $this->status = 0;
     if (isset($additional_headers["Content-Type"])) {
         $ContentType = $additional_headers["Content-Type"];
         unset($additional_headers["Content-Type"]);
     } else {
         $ContentType = $content != "" ? 'text/plain' : '';
     }
     foreach ($this->set_headers as $key => $value) {
         $additional_headers[$key] = $value;
     }
     if (array_key_exists("SESSION_TOKEN", $arSettings)) {
         $additional_headers["x-amz-security-token"] = $arSettings["SESSION_TOKEN"];
     }
     ksort($additional_headers);
     $RequestURI = $file_name;
     $obRequest = new CHTTP();
     if (isset($additional_headers["option-file-result"])) {
         $obRequest->fp = $additional_headers["option-file-result"];
     }
     foreach ($this->SignRequest($arSettings, $verb, $bucket, $file_name, $ContentType, $additional_headers) as $key => $value) {
         $obRequest->additional_headers[$key] = $value;
     }
     foreach ($additional_headers as $key => $value) {
         if (preg_match("/^option-/", $key) == 0) {
             $obRequest->additional_headers[$key] = $value;
         }
     }
     if ($this->new_end_point != "" && preg_match('#^(http|https)://' . preg_quote($bucket, '#') . '(.+?)/#', $this->new_end_point, $match) > 0) {
         $host = $bucket . $match[2];
     } elseif ($this->location) {
         $host = $bucket . "." . $this->location . ".amazonaws.com";
     } else {
         $host = $bucket . ".s3.amazonaws.com";
     }
     $was_end_point = $this->new_end_point;
     $this->new_end_point = '';
     $obRequest->Query($verb, $host, 80, $RequestURI . $params, $content, '', $ContentType);
     $this->status = $obRequest->status;
     $this->host = $host;
     $this->verb = $verb;
     $this->url = $RequestURI . $params;
     $this->headers = $obRequest->headers;
     $this->errno = $obRequest->errno;
     $this->errstr = $obRequest->errstr;
     $this->result = $obRequest->result;
     if ($obRequest->status == 200) {
         if (isset($additional_headers["option-raw-result"]) || isset($additional_headers["option--result"])) {
             return $obRequest->result;
         } elseif ($obRequest->result != "") {
             $obXML = new CDataXML();
             $text = preg_replace("/<" . "\\?XML.*?\\?" . ">/i", "", $obRequest->result);
             if ($obXML->LoadString($text)) {
                 $arXML = $obXML->GetArray();
                 if (is_array($arXML)) {
                     return $arXML;
                 }
             }
             //XML parse error
             $e = new CApplicationException(GetMessage('CLO_STORAGE_S3_XML_PARSE_ERROR', array('#errno#' => '1')));
             $APPLICATION->ThrowException($e);
             return false;
         } else {
             //Empty success result
             return array();
         }
     } elseif ($obRequest->status == 307 && isset($obRequest->headers["Location"]) && $was_end_point === "") {
         $this->new_end_point = $obRequest->headers["Location"];
         return $this->SendRequest($arSettings, $verb, $bucket, $file_name, $params, $content, $additional_headers);
     } elseif ($obRequest->status > 0) {
         if ($obRequest->result != "") {
             $obXML = new CDataXML();
             if ($obXML->LoadString($obRequest->result)) {
                 $node = $obXML->SelectNodes("/Error/Message");
                 if (is_object($node)) {
                     $errmsg = trim($node->textContent(), '.');
                     $e = new CApplicationException(GetMessage('CLO_STORAGE_S3_XML_ERROR', array('#errmsg#' => $errmsg)));
                     $APPLICATION->ThrowException($e);
                     return false;
                 }
             }
         }
         $e = new CApplicationException(GetMessage('CLO_STORAGE_S3_XML_PARSE_ERROR', array('#errno#' => '2')));
         $APPLICATION->ThrowException($e);
         return false;
     } else {
         $e = new CApplicationException(GetMessage('CLO_STORAGE_S3_XML_PARSE_ERROR', array('#errno#' => '3')));
         $APPLICATION->ThrowException($e);
         return false;
     }
 }
Ejemplo n.º 14
0
 $out = "";
 $out .= "POST " . $path . " HTTP/1.1\r\n";
 $out .= "Host: " . $host . " \r\n";
 $out .= "Content-Type: application/soap+xml; charset=" . LANG_CHARSET . "\r\n";
 $out .= "Content-length: " . strlen($query) . "\r\n\r\n";
 $out .= $query;
 $out .= "\r\n";
 fputs($fp, $out);
 while (!feof($fp)) {
     $content .= fgets($fp, 128);
 }
 fclose($fp);
 if (strlen($content) > 0) {
     require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
     $objXML = new CDataXML();
     $objXML->LoadString($content);
     $arResult = $objXML->GetArray();
     if (!empty($arResult)) {
         $method = $arResult["Envelope"]["#"]["Body"][0]["#"]["checkBillResponse"];
         if (!empty($method)) {
             if ($arOrder = CSaleOrder::GetByID($orderID)) {
                 $phone = $method[0]["#"]["user"][0]["#"];
                 $amount = $method[0]["#"]["amount"][0]["#"];
                 $date = $method[0]["#"]["date"][0]["#"];
                 $status = $method[0]["#"]["status"][0]["#"];
                 //$strPS_STATUS_DESCRIPTION = GetMessage("SALE_STATUS")." - ".$status." (".GetMessage("CLASS_STATUS_".$status).")"." ; ";
                 $strPS_STATUS_DESCRIPTION = GetMessage("SALE_STATUS_PHONE") . " - " . $phone . "; ";
                 $strPS_STATUS_DESCRIPTION .= GetMessage("SALE_STATUS_AMOUNT") . " - " . $amount . "; ";
                 $strPS_STATUS_DESCRIPTION .= GetMessage("SALE_STATUS_DATE") . " - " . $date . "; ";
                 $strPS_STATUS_MESSAGE = GetMessage("CLASS_STATUS_" . $status);
                 $arFields = array("PS_STATUS" => $status == 60 ? "Y" : "N", "PS_STATUS_CODE" => $status, "PS_STATUS_DESCRIPTION" => $strPS_STATUS_DESCRIPTION, "PS_STATUS_MESSAGE" => $strPS_STATUS_MESSAGE, "PS_RESPONSE_DATE" => Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG))));
Ejemplo n.º 15
0
 function GetBoardFromSite($queryParameters)
 {
     $result = array();
     $result = CAirportBoard::GetOneBoardFromSite($queryParameters, "");
     $res = $result["HTML"];
     unset($result["HTML"]);
     /*// Ниже код для загрузки табло за сутки (используется три запроса с последующей склейкой)
       $result = CAirportBoard::GetOneBoardFromSite( $queryParameters, "v=3" );
       $res = $result["HTML"];
       unset($result["HTML"]);
       $result2 = CAirportBoard::GetOneBoardFromSite( $queryParameters, "v=11" );
       $res .= $result2["HTML"];
       unset($result2["HTML"]);
       $result3 = CAirportBoard::GetOneBoardFromSite( $queryParameters, "v=19" );
       $res .= $result3["HTML"];
       unset($result3["HTML"]);
       
       if ( intval($result2["ERROR"]["CODE"]) )
       {
         $result["ERROR"] = $result2["ERROR"];
       } elseif ( intval($result3["ERROR"]["CODE"]) )
       {
         $result["ERROR"] = $result3["ERROR"];
       }
       */
     if (!intval($result["ERROR"]["CODE"])) {
         $res = '<table>' . $res . '</table>';
         $res = str_replace("<br>", " ", $res);
         $res = str_replace("<nobr>", "", $res);
         $res = str_replace("</nobr>", "", $res);
         //trace($res);
         $xml = new CDataXML();
         if ($xml->LoadString($res)) {
             $node = $xml->SelectNodes("/table");
             $rows = $node->elementsByName("tr");
             $akNames = array();
             $akCodes = array();
             $departures = array();
             $arrivals = array();
             $terminals = array();
             $i = 0;
             foreach ($rows as $row) {
                 if (strstr($row->getAttribute("class"), "tr0")) {
                     $cells = $row->elementsByName("td");
                     // Определяем код авиакомпании и номер рейса
                     preg_match_all("/([A-Za-zА-Яа-я0-9]{2})\\s*([0-9]+)\\s*/", $cells[0]->content, $flightNumber, PREG_PATTERN_ORDER);
                     $cityPatterns = array("/([\\W\\d]+)\\(/", "/\\s+\\)\\s*/");
                     $cityReplace = array("\$1 (", ")");
                     $result["FLIGHTS"][$i] = array("FLIGHT" => array("AK_CODE" => $flightNumber[1][0], "NUMBER" => $flightNumber[2][0]), "AK_NAME" => "", "DEPARTURE" => htmlspecialcharsEx(preg_replace($cityPatterns, $cityReplace, $cells[1]->content)), "ARRIVAL" => htmlspecialcharsEx(preg_replace($cityPatterns, $cityReplace, $cells[1]->content)), "STATUS" => CAirportBoard::GetStatusInfo($cells[5]->content), "TIME" => array("PLANNED" => CAirportBoard::GetDateTimeArray($cells[2]->content), "ESTIMATED" => "", "ACTUAL" => CAirportBoard::GetDateTimeArray($cells[3]->content)), "TERMINAL" => "");
                     // Формируем список уникальных терминалов и пунктов вылета и прилета для фильтра
                     if (!in_array($flightNumber[1][0], $akCodes)) {
                         $akCodes[] = $flightNumber[1][0];
                     }
                     if (!in_array($result["FLIGHTS"][$i]["DEPARTURE"], $departures)) {
                         $departures[] = $result["FLIGHTS"][$i]["DEPARTURE"];
                     }
                     if (!in_array($result["FLIGHTS"][$i]["ARRIVAL"], $arrivals)) {
                         $arrivals[] = $result["FLIGHTS"][$i]["ARRIVAL"];
                     }
                     $i++;
                 }
             }
             sort($akNames);
             sort($akCodes);
             sort($departures);
             sort($arrivals);
             sort($terminals);
             $result["AK_NAMES"] = $akNames;
             $result["AK_CODES"] = $akCodes;
             $result["DEPARTURES"] = $departures;
             $result["ARRIVALS"] = $arrivals;
             $result["TERMINALS"] = $terminals;
         }
     }
     return $result;
 }
Ejemplo n.º 16
0
function gdGetRss($rss_url, $cache_time = 0)
{
    /** @global CMain $APPLICATION */
    global $APPLICATION;
    $cache = new CPHPCache();
    if (!$cache->StartDataCache($cache_time, 'c' . $rss_url, "gdrss")) {
        $v = $cache->GetVars();
        return $v['oRss'];
    }
    $oRssFeeds = new gdRssFeeds();
    $ob = new CHTTP();
    $ob->http_timeout = 10;
    $ob->setFollowRedirect(true);
    $ob->HTTPQuery("GET", $rss_url);
    $res = $ob->result;
    if (!$res) {
        $cache->EndDataCache(array("oRss" => false));
        return false;
    }
    if (preg_match("/<" . "\\?XML[^>]{1,}encoding=[\"']([^>\"']{1,})[\"'][^>]{0,}\\?" . ">/i", $res, $matches)) {
        $charset = trim($matches[1]);
        $res = $APPLICATION->ConvertCharset($res, $charset, SITE_CHARSET);
    }
    $xml = new CDataXML();
    $xml->LoadString($res);
    $oNode = $xml->SelectNodes("/rss/channel/title");
    if (!$oNode) {
        $cache->EndDataCache(array("oRss" => false));
        return false;
    }
    $oRssFeeds->title = $oNode->content;
    if (trim($oRssFeeds->title) == '') {
        if ($oSubNode = $oNode->elementsByName("cdata-section")) {
            $oRssFeeds->title = $oSubNode[0]->content;
        }
    }
    if ($oNode = $xml->SelectNodes("/rss/channel/link")) {
        $oRssFeeds->link = $oNode->content;
    }
    if ($oNode = $xml->SelectNodes("/rss/channel/description")) {
        $oRssFeeds->description = $oNode->content;
    }
    if (trim($oRssFeeds->description) == '') {
        if ($oNode && ($oSubNode = $oNode->elementsByName("cdata-section"))) {
            $oRssFeeds->description = $oSubNode[0]->content;
        }
    }
    if ($oNode = $xml->SelectNodes("/rss/channel/pubDate")) {
        $oRssFeeds->pubDate = $oNode->content;
    } elseif ($oNode = $xml->SelectNodes("/rss/channel/lastBuildDate")) {
        $oRssFeeds->pubDate = $oNode->content;
    }
    if ($oNode = $xml->SelectNodes("/rss/channel")) {
        $oNodes = $oNode->elementsByName("item");
        foreach ($oNodes as $oNode) {
            $item = array();
            if ($oSubNode = $oNode->elementsByName("title")) {
                $item["TITLE"] = $oSubNode[0]->content;
            }
            if (trim($item["TITLE"]) == '' && !empty($oSubNode)) {
                if ($oSubNode = $oSubNode[0]->elementsByName("cdata-section")) {
                    $item["TITLE"] = $oSubNode[0]->content;
                }
            }
            if ($oSubNode = $oNode->elementsByName("link")) {
                $item["LINK"] = $oSubNode[0]->content;
            }
            if ($oSubNode = $oNode->elementsByName("pubDate")) {
                $item["PUBDATE"] = $oSubNode[0]->content;
            }
            if ($oSubNode = $oNode->elementsByName("description")) {
                $item["DESCRIPTION"] = $oSubNode[0]->content;
            }
            if (trim($item["DESCRIPTION"]) == '' && !empty($oSubNode)) {
                if ($oSubNode = $oSubNode[0]->elementsByName("cdata-section")) {
                    $item["DESCRIPTION"] = $oSubNode[0]->content;
                }
            }
            if ($oSubNode = $oNode->elementsByName("author")) {
                $item["AUTHOR"] = $oSubNode[0]->content;
            }
            if (trim($item["AUTHOR"]) == '' && !empty($oSubNode)) {
                if ($oSubNode = $oSubNode[0]->elementsByName("cdata-section")) {
                    $item["AUTHOR"] = $oSubNode[0]->content;
                }
            }
            $oRssFeeds->items[] = $item;
        }
    }
    $cache->EndDataCache(array("oRss" => $oRssFeeds));
    return $oRssFeeds;
}
Ejemplo n.º 17
0
} else {
    $url = 'ts=' . mktime();
}
$cache = new CPageCache();
if ($arGadgetParams["CACHE_TIME"] > 0 && !$cache->StartDataCache($arGadgetParams["CACHE_TIME"], 'c' . $arGadgetParams["CITY"], "gdprobki")) {
    return;
}
$ob = new CHTTP();
$ob->http_timeout = 10;
$ob->Query("GET", "export.yandex.ru", 80, "/bar/reginfo.xml?" . $url, false, "", "N");
$errno = $ob->errno;
$errstr = $ob->errstr;
$res = $ob->result;
$res = str_replace("−", "-", $res);
$xml = new CDataXML();
$xml->LoadString($APPLICATION->ConvertCharset($res, 'UTF-8', SITE_CHARSET));
$node = $xml->SelectNodes('/info/traffic/title');
?>
<h3><?php 
echo $node->content;
?>
</h3>
<table width="90%"><tr>
<td width="80%" nowrap>
<?php 
$node = $xml->SelectNodes('/info/traffic/hint');
?>
<span class="gdtrafic"><?php 
echo $node->content;
?>
</span><br>
Ejemplo n.º 18
0
// при ошибке запроса
if ($client->getResponseThemeName() == 'error') {
    CHTTP::SetStatus("404 Not Found");
    // TODO: получать message из ответа сервера
    ShowError(GetMessage('MAX_NOT_FOUND'));
    return;
}
if (mb_strtolower(SITE_CHARSET) != 'utf-8') {
    $data = iconv('utf-8', SITE_CHARSET, $domXml);
} else {
    $data = $domXml;
}
$xml = new CDataXML();
// Лучше бы через
// $xml->Load('/path/to/file');
$xml->LoadString($data);
// получаем данные
/**
 * В минимальном варианте:
 * - фото
 * - марка
 * - модель
 * - год выпуска
 * + объём двигателя
 * - пробег
 * - цена
 */
$arVehicles = array();
$xmlVehicles = $xml->SelectNodes('/response/vehicles');
$i = 0;
if ($xmlVehicles && is_object($xmlVehicles)) {
Ejemplo n.º 19
0
 if (method_exists($adminMenu, "IsSectionActive")) {
     if ($adminMenu->IsSectionActive("menu_marketplace")) {
         $CACHE = 60 * 60 * 24;
         $obCache = new CPHPCache();
         $cache_id = "main_menu_marketplace_" . LANGUAGE_ID;
         if ($obCache->InitCache($CACHE, $cache_id, "/")) {
             $vars = $obCache->GetVars();
             $arMarket = $vars["arMarket"];
         } else {
             $ht = new Bitrix\Main\Web\HttpClient(array("socketTimeout" => 30));
             if ($res = $ht->get("http://marketplace.1c-bitrix.ru/data_export.php")) {
                 if ($ht->getStatus() == "200") {
                     $res = $APPLICATION->ConvertCharset($res, "windows-1251", SITE_CHARSET);
                     require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
                     $objXML = new CDataXML();
                     $objXML->LoadString($res);
                     $arResult = $objXML->GetArray();
                     if (!empty($arResult) && is_array($arResult)) {
                         if (!empty($arResult["categories"]["#"]["category"])) {
                             foreach ($arResult["categories"]["#"]["category"] as $category) {
                                 $arCategory = array();
                                 $arUrls = array();
                                 if (!empty($category["#"]["items"][0]["#"]["item"])) {
                                     foreach ($category["#"]["items"][0]["#"]["item"] as $catIn) {
                                         $url = "update_system_market.php?category=" . $catIn["#"]["id"][0]["#"];
                                         $arCategory[] = array("text" => $catIn["#"]["name"][0]["#"] . " (" . $catIn["#"]["count"][0]["#"] . ")", "title" => GetMessage("MAIN_MENU_MP_CATEGORY") . " " . $catIn["#"]["name"][0]["#"], "url" => $url . "&lang=" . LANGUAGE_ID);
                                         $arUrls[] = $url;
                                     }
                                 }
                                 if (IntVal($category["#"]["id"][0]["#"]) > 0) {
                                     $url = "update_system_market.php?category=" . $category["#"]["id"][0]["#"];
Ejemplo n.º 20
0
	public function ListFiles($arBucket, $filePath, $bRecursive = false)
	{
		global $APPLICATION;

		$result = array(
			"dir" => array(),
			"file" => array(),
			"file_size" => array(),
		);

		$filePath = trim($filePath, '/');
		if(strlen($filePath))
			$filePath .= '/';

		if($arBucket["PREFIX"])
		{
			if(substr($filePath, 0, strlen($arBucket["PREFIX"])+2) != "/".$arBucket["PREFIX"]."/")
				$filePath = $arBucket["PREFIX"]."/".ltrim($filePath, "/");
		}
		$filePath = $APPLICATION->ConvertCharset($filePath, LANG_CHARSET, "UTF-8");

		$marker = '';
		$new_marker = false;
		while(true)
		{
			$obRequest = $this->SendRequest(
				$arBucket["SETTINGS"],
				"GET",
				$arBucket["BUCKET"],
				'/',
				$s='?format=xml&'.($bRecursive? '': '&delimiter=/').'&prefix='.urlencode($filePath).'&marker='.urlencode($marker)
			);
			$bFound = false;
			if(is_object($obRequest) && $obRequest->result && $this->status == 200)
			{
				$obXML = new CDataXML;
				$text = preg_replace("/<"."\\?XML.*?\\?".">/i", "", $obRequest->result);
				if($obXML->LoadString($text))
				{
					$arXML = $obXML->GetArray();
					if(
						isset($arXML["container"])
						&& is_array($arXML["container"])
						&& isset($arXML["container"]["#"])
						&& is_array($arXML["container"]["#"])
						&& !empty($arXML["container"]["#"])
					)
					{
						if(
							isset($arXML["container"]["#"]["object"])
							&& is_array($arXML["container"]["#"]["object"])
							&& !empty($arXML["container"]["#"]["object"])
						)
						{
							$bFound = true;
							foreach($arXML["container"]["#"]["object"] as $a)
							{
								$new_marker = $a["#"]["name"][0]["#"];
								if($a["#"]["content_type"][0]["#"] === "application/directory")
								{
									$dir_name = trim(substr($a["#"]["name"][0]["#"], strlen($filePath)), "/");
									$result["dir"][$APPLICATION->ConvertCharset(urldecode($dir_name), "UTF-8", LANG_CHARSET)] = true;
								}
								else
								{
									$file_name = substr($a["#"]["name"][0]["#"], strlen($filePath));
									$file_name = $APPLICATION->ConvertCharset(urldecode($file_name), "UTF-8", LANG_CHARSET);
									if (!in_array($file_name, $result["file"]))
									{
										$result["file"][] = $file_name;
										$result["file_size"][] = $a["#"]["bytes"][0]["#"];
									}
								}
							}
						}

						if(
							isset($arXML["container"]["#"]["subdir"])
							&& is_array($arXML["container"]["#"]["subdir"])
							&& !empty($arXML["container"]["#"]["subdir"])
						)
						{
							$bFound = true;
							foreach($arXML["container"]["#"]["subdir"] as $a)
							{
								$new_marker = $a["@"]["name"];
								$dir_name = trim(substr($a["@"]["name"], strlen($filePath)), "/");
								$result["dir"][$APPLICATION->ConvertCharset(urldecode($dir_name), "UTF-8", LANG_CHARSET)] = true;
							}
						}
					}
				}
			}
			else
			{
				return false;
			}

			if($new_marker === $marker)
				break;

			if(!$bFound)
				break;

			$marker = $new_marker;
		}
		$result["dir"] = array_keys($result["dir"]);
		return $result;
	}
Ejemplo n.º 21
0
 function SendRequest($access_key, $secret_key, $verb, $bucket, $file_name = '/', $params = '', $content = '', $additional_headers = array())
 {
     global $APPLICATION;
     $this->status = 0;
     if (isset($additional_headers["Content-Type"])) {
         $ContentType = $additional_headers["Content-Type"];
         unset($additional_headers["Content-Type"]);
     } else {
         $ContentType = $content ? 'text/plain' : '';
     }
     if (!array_key_exists("x-goog-api-version", $additional_headers)) {
         $additional_headers["x-goog-api-version"] = "1";
     }
     $RequestMethod = $verb;
     $RequestURI = $file_name;
     $RequestDATE = gmdate('D, d M Y H:i:s', time()) . ' GMT';
     //Prepare Signature
     $CanonicalizedAmzHeaders = "";
     ksort($additional_headers);
     foreach ($additional_headers as $key => $value) {
         if (preg_match("/^x-goog-/", $key)) {
             $CanonicalizedAmzHeaders .= $key . ":" . $value . "\n";
         }
     }
     $CanonicalizedResource = "/" . $bucket . $RequestURI;
     $StringToSign = "{$RequestMethod}\n\n{$ContentType}\n{$RequestDATE}\n{$CanonicalizedAmzHeaders}{$CanonicalizedResource}";
     //$utf = $APPLICATION->ConvertCharset($StringToSign, LANG_CHARSET, "UTF-8");
     $Signature = base64_encode($this->hmacsha1($StringToSign, $secret_key));
     $Authorization = "GOOG1 " . $access_key . ":" . $Signature;
     $obRequest = new CHTTP();
     $obRequest->additional_headers["Date"] = $RequestDATE;
     $obRequest->additional_headers["Authorization"] = $Authorization;
     foreach ($additional_headers as $key => $value) {
         if (!preg_match("/^option-/", $key)) {
             $obRequest->additional_headers[$key] = $value;
         }
     }
     if ($this->new_end_point && preg_match('#^(http|https)://' . preg_quote($bucket, '#') . '(.+)/#', $this->new_end_point, $match)) {
         $host = $match[2];
     } else {
         $host = $bucket . ".commondatastorage.googleapis.com";
     }
     $was_end_point = $this->new_end_point;
     $this->new_end_point = '';
     $obRequest->Query($RequestMethod, $host, 80, $RequestURI . $params, $content, '', $ContentType);
     $this->status = $obRequest->status;
     $this->headers = $obRequest->headers;
     $this->errno = $obRequest->errno;
     $this->errstr = $obRequest->errstr;
     $this->result = $obRequest->result;
     if ($obRequest->status == 200) {
         if (isset($additional_headers["option-raw-result"])) {
             return $obRequest->result;
         } elseif ($obRequest->result) {
             $obXML = new CDataXML();
             $text = preg_replace("/<" . "\\?XML.*?\\?" . ">/i", "", $obRequest->result);
             if ($obXML->LoadString($text)) {
                 $arXML = $obXML->GetArray();
                 if (is_array($arXML)) {
                     return $arXML;
                 }
             }
             //XML parse error
             $APPLICATION->ThrowException(GetMessage('CLO_STORAGE_GOOGLE_XML_PARSE_ERROR', array('#errno#' => 1)));
             return false;
         } else {
             //Empty success result
             return array();
         }
     } elseif ($obRequest->status == 307 && isset($obRequest->headers["Location"]) && !$was_end_point) {
         $this->new_end_point = $obRequest->headers["Location"];
         return $this->SendRequest($access_key, $secret_key, $verb, $bucket, $file_name, $params, $content, $additional_headers);
     } elseif ($obRequest->status > 0) {
         if ($obRequest->result) {
             $obXML = new CDataXML();
             if ($obXML->LoadString($obRequest->result)) {
                 $arXML = $obXML->GetArray();
                 if (is_array($arXML) && is_string($arXML["Error"]["#"]["Message"][0]["#"])) {
                     $APPLICATION->ThrowException(GetMessage('CLO_STORAGE_GOOGLE_XML_ERROR', array('#errmsg#' => trim($arXML["Error"]["#"]["Message"][0]["#"], '.'))));
                     return false;
                 }
             }
         }
         $APPLICATION->ThrowException(GetMessage('CLO_STORAGE_GOOGLE_XML_PARSE_ERROR', array('#errno#' => 2)));
         return false;
     } else {
         $APPLICATION->ThrowException(GetMessage('CLO_STORAGE_GOOGLE_XML_PARSE_ERROR', array('#errno#' => 3)));
         return false;
     }
 }
Ejemplo n.º 22
0
 function LoadFromStr($strXML)
 {
     if (strlen($strXML) <= 0) {
         $this->props = 'all';
         return true;
     }
     $objXML = new CDataXML();
     $objXML->delete_ns = false;
     if (!$objXML->LoadString($strXML)) {
         $this->success = false;
         return false;
     }
     $this->_array = $objXML->GetArray();
     $this->parse_array($this->_array);
     return $this->success;
 }
Ejemplo n.º 23
0
 function decodeStream($request, $stream)
 {
     global $APPLICATION;
     $stream_cutted = $this->stripHTTPHeader($stream);
     if (!$stream_cutted or !class_exists("CDataXML")) {
         $APPLICATION->ThrowException("Error: BitrixXMLParser. " . "Downloaded page: <br>" . htmlspecialcharsEx($stream));
         return;
     }
     $stream = $stream_cutted;
     $xml = new CDataXML();
     $stream = $APPLICATION->ConvertCharset($stream, "UTF-8", SITE_CHARSET);
     if (!$xml->LoadString($stream)) {
         $APPLICATION->ThrowException("Error: Can't parse request xml data. ");
         return;
     }
     $dom = $xml->GetTree();
     $this->DOMDocument = $dom;
     if (get_class($dom) == "CDataXMLDocument" || get_class($dom) == "cdataxmldocument") {
         // check for fault
         $response = $dom->elementsByName('Fault');
         if (count($response) == 1) {
             $this->IsFault = 1;
             $faultStringArray = $dom->elementsByName("faultstring");
             $this->FaultString = $faultStringArray[0]->textContent();
             $faultCodeArray = $dom->elementsByName("faultcode");
             $this->FaultCode = $faultCodeArray[0]->textContent();
             return;
         }
         // get the response
         $body = $dom->elementsByName("Body");
         $body = $body[0];
         $response = $body->children();
         $response = $response[0];
         if (get_class($response) == "CDataXMLNode" || get_class($response) == "cdataxmlnode") {
             /*Cut from the SOAP spec:
             				The method response is viewed as a single struct containing an accessor
             				for the return value and each [out] or [in/out] parameter.
             				The first accessor is the return value followed by the parameters
             				in the same order as in the method signature.
             
             				Each parameter accessor has a name corresponding to the name
             				of the parameter and type corresponding to the type of the parameter.
             				The name of the return value accessor is not significant.
             				Likewise, the name of the struct is not significant.
             				However, a convention is to name it after the method name
             				with the string "Response" appended.
             				*/
             $responseAccessors = $response->children();
             //echo '<pre>'; print_r($responseAccessors); echo '</pre>';
             if (count($responseAccessors) > 0) {
                 $this->Value = array();
                 foreach ($responseAccessors as $arChild) {
                     $value = $arChild->decodeDataTypes();
                     $this->Value = array_merge($this->Value, $value);
                 }
             }
         } else {
             $APPLICATION->ThrowException("Could not understand type of class decoded");
         }
     } else {
         $APPLICATION->ThrowException("Could not process XML in response");
     }
 }
Ejemplo n.º 24
0
 function Calculate($profile, $arConfig, $arOrder, $STEP)
 {
     if ($STEP >= 3) {
         return array("RESULT" => "ERROR", "TEXT" => GetMessage('SALE_DH_CPCR_ERROR_CONNECT'));
     }
     $arOrder["WEIGHT"] = CSaleMeasure::Convert($arOrder["WEIGHT"], "G", "KG");
     if ($arOrder["WEIGHT"] <= 0) {
         $arOrder["WEIGHT"] = 1;
     }
     // weight must not be null - let it be 1 kg
     $arLocationFrom = CDeliveryCPCR::__GetLocation($arOrder["LOCATION_FROM"]);
     $arLocationTo = CDeliveryCPCR::__GetLocation($arOrder["LOCATION_TO"]);
     // caching is dependent from category, locations "from" & "to" and from weight interval
     $cache_id = "sale3|9.5.0|cpcr|" . $arConfig["category"]['VALUE'] . "|" . $arLocationFrom["ORIGINAL"]["COUNTRY_ID"] . "|" . $arLocationFrom["ORIGINAL"]["CITY_ID"] . "|" . $arLocationTo["ORIGINAL"]["COUNTRY_ID"] . "|" . $arLocationTo["ORIGINAL"]["CITY_ID"];
     if ($arOrder["WEIGHT"] <= 0.5) {
         $cache_id .= "|0";
     } elseif ($arOrder["WEIGHT"] <= 1) {
         $cache_id .= "|1";
     } else {
         $cache_id .= "|" . ceil($arOrder["WEIGHT"]);
     }
     // other intervals - up to next natural number
     $obCache = new CPHPCache();
     if ($obCache->InitCache(DELIVERY_CPCR_CACHE_LIFETIME, $cache_id, "/")) {
         // cache found
         $vars = $obCache->GetVars();
         $arResult = $vars["RESULT"];
     } else {
         // format HTTP query request data
         $arQuery = array();
         $arQuery[] = DELIVERY_CPCR_SERVER_POST_FROM_COUNTRY . "=" . urlencode($arLocationFrom["COUNTRY"]);
         if (is_set($arLocationFrom["CITY_ID"])) {
             $arQuery[] = DELIVERY_CPCR_SERVER_POST_FROM_CITY . "=" . urlencode($arLocationFrom["CITY_ID"]);
         } else {
             $arQuery[] = DELIVERY_CPCR_SERVER_POST_FROM_CITY_NAME . "=" . urlencode($GLOBALS['APPLICATION']->ConvertCharset($arLocationFrom["CITY"], LANG_CHARSET, 'windows-1251'));
         }
         $arQuery[] = DELIVERY_CPCR_SERVER_POST_WEIGHT . "=" . urlencode($arOrder["WEIGHT"]);
         $arQuery[] = DELIVERY_CPCR_SERVER_POST_CATEGORY . "=" . "1";
         //urlencode($arConfig["category"]["VALUE"]);
         // price coefficient will be added later - to make caching independent from price
         $arQuery[] = DELIVERY_CPCR_SERVER_POST_PRICE . "=0";
         $arQuery[] = DELIVERY_CPCR_SERVER_POST_TO_COUNTRY . "=" . urlencode($arLocationTo["COUNTRY"]);
         /*
         if (is_set($arLocationTo["REGION"]))
         	$arQuery[] = DELIVERY_CPCR_SERVER_POST_TO_REGION."=".urlencode($arLocationTo["REGION"]);
         else
         	$arQuery[] = DELIVERY_CPCR_SERVER_POST_TO_REGION."=".urlencode(DELIVERY_CPCR_CITY_DEFAULT);
         */
         if (is_set($arLocationTo["CITY_ID"])) {
             $arQuery[] = DELIVERY_CPCR_SERVER_POST_TO_CITY . "=" . urlencode($arLocationTo["CITY_ID"]);
         } else {
             $arQuery[] = DELIVERY_CPCR_SERVER_POST_TO_CITY_NAME . "=" . urlencode($GLOBALS['APPLICATION']->ConvertCharset($arLocationTo["CITY"], LANG_CHARSET, 'windows-1251'));
         }
         CDeliveryCPCR::__Write2Log(print_r($arLocationTo, true));
         $arQuery[] = DELIVERY_CPCR_SERVER_POST_ADDITIONAL;
         $query_string = implode("&", $arQuery);
         $query_page = DELIVERY_CPCR_SERVER_PAGE;
         // get data from server
         $ob = new CHTTP();
         $ob->http_timeout = 50;
         $data = $ob->Query(DELIVERY_CPCR_SERVER_METHOD, DELIVERY_CPCR_SERVER, DELIVERY_CPCR_SERVER_PORT, $query_page . (DELIVERY_CPCR_SERVER_METHOD == 'GET' ? (strpos($query_page, '?') === false ? '?' : '&') . $query_string : ''), DELIVERY_CPCR_SERVER_METHOD == 'POST' ? $query_string : false);
         if ($data) {
             $data = $GLOBALS["APPLICATION"]->ConvertCharset($ob->result, 'windows-1251', LANG_CHARSET);
         }
         CDeliveryCPCR::__Write2Log($query_page);
         CDeliveryCPCR::__Write2Log($query_string);
         CDeliveryCPCR::__Write2Log($error_number . ": " . $error_text);
         CDeliveryCPCR::__Write2Log($data);
         if (strpos($data, "<?xml") === false) {
             return array("RESULT" => "ERROR", "TEXT" => GetMessage('SALE_DH_CPCR_ERROR_CONNECT'));
         }
         require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
         $objXML = new CDataXML();
         $objXML->LoadString($data);
         $arResult = $objXML->GetArray();
         $arProfiles = array('SIMPLE' => '"цеоюпд-щйяопеяя"', 'ECONOM' => '"оекхйюм-ярюмдюпр"', 'SIMPLE13' => '"цеоюпд-щйяопеяя 13"', 'SIMPLE18' => '"цеоюпд-щйяопеяя 18"', 'BIZON' => '"ахгнм-йюпцн"', 'COLIBRI' => '"йнкхапх-днйслемр"', 'PELICAN' => '"оекхйюм-нмкюим"', 'FRAXT' => '"тпюур"');
         $arTmpResult = array();
         if (isset($arResult["root"]["#"]["Error"]) and is_array($arResult["root"]["#"]["Error"])) {
             return array("RESULT" => "ERROR", "TEXT" => GetMessage('SALE_DH_CPCR_ERROR_CONNECT') . ' (' . htmlspecialcharsbx(strip_tags($arResult["root"]["#"]["Tariff"][0]["#"]["TariffType"][0]["#"])) . ')');
         } else {
             if (!empty($arResult["root"]["#"]["Tariff"])) {
                 foreach ($arResult["root"]["#"]["Tariff"] as $key => $val) {
                     foreach ($val["#"] as $k => $v) {
                         foreach ($arProfiles as $prof => $title) {
                             if (ToUpper($v[0]["#"]) == ToUpper($title)) {
                                 $arTmpResult[ToLower($prof)] = array('VALUE' => $val["#"]["Total_Dost"][0]["#"], 'TRANSIT' => $val["#"]["DP"][0]["#"]);
                                 unset($arProfiles[$prof]);
                                 break;
                             }
                         }
                     }
                 }
             }
             $arResult = $arTmpResult;
             if (count($arTmpResult) > 0) {
                 $obCache->StartDataCache();
                 $obCache->EndDataCache(array("RESULT" => $arResult));
             } else {
                 return array("RESULT" => "ERROR", "TEXT" => GetMessage('SALE_DH_CPCR_ERROR_CONNECT'));
             }
         }
     }
     if (is_array($arResult[$profile])) {
         $arResult[$profile]['RESULT'] = 'OK';
         // it's starnge but it seems that CPCR new calculator doesnt count insurance tax at all. so, temporarily comment this line.
         // TODO: check this later
         //$arResult[$profile]['VALUE'] += $arOrder["PRICE"] * DELIVERY_CPCR_PRICE_TARIFF
         return $arResult[$profile];
     } else {
         return array("RESULT" => "ERROR", "TEXT" => GetMessage('SALE_DH_CPCR_ERROR_RESPONSE'));
     }
 }
Ejemplo n.º 25
0
 function ProcessRequest()
 {
     global $HTTP_SERVER_VARS, $APPLICATION;
     if ($HTTP_SERVER_VARS["REQUEST_METHOD"] != "POST" or !class_exists("CDataXML")) {
         $this->ShowSOAPFault("Error: this web page does only understand POST methods. BitrixXMLParser. ");
     }
     for ($i = 0; $i < count($this->OnRequestEvent); $i++) {
         $this->OnRequestEvent[$i]->OnBeforeRequest($this);
     }
     //AddMessage2Log($this->RawPostData);
     $xmlData = $this->stripHTTPHeader($this->RawPostData);
     $xmlData = $APPLICATION->ConvertCharset($xmlData, "UTF-8", SITE_CHARSET);
     $xml = new CDataXML();
     //AddMessage2Log($xmlData);
     if (!$xml->LoadString($xmlData)) {
         $this->ShowSOAPFault("Error: Can't parse request xml data. ");
     }
     $dom = $xml->GetTree();
     // Check for non-parsing XML, to avoid call to non-object error.
     if (!is_object($dom)) {
         $this->ShowSOAPFault("Bad XML");
     }
     // add namespace fetching on body
     // get the SOAP body
     $body = $dom->elementsByName("Body");
     $children = $body[0]->children();
     if (count($children) == 1) {
         $requestNode = $children[0];
         $requestParsed = false;
         // get target namespace for request
         // it often function request message. in wsdl gen. = function+"request"
         $functionName = $requestNode->name();
         $namespaceURI = $requestNode->namespaceURI();
         for ($i = 0; $i < count($this->OnRequestEvent); $i++) {
             if ($this->OnRequestEvent[$i]->ProcessRequestBody($this, $requestNode)) {
                 $requestParsed = true;
                 break;
             }
         }
         for ($i = 0; $i < count($this->OnRequestEvent); $i++) {
             $this->OnRequestEvent[$i]->OnAfterResponse($this);
         }
         if (!$requestParsed) {
             $this->ShowSOAPFault('Unknown operation requested.');
         }
         return $requestParsed;
     } else {
         $this->ShowSOAPFault('"Body" element in the request has wrong number of children');
     }
     return false;
 }
Ejemplo n.º 26
0
function gdGetRss($rss_url, $cache_time = 0)
{
    $cache = new CPHPCache();
    if (!$cache->StartDataCache($cache_time, 'c' . $rss_url, "gdrss")) {
        $v = $cache->GetVars();
        return $v['oRss'];
    }
    $oRssFeeds = new gdRssFeeds();
    $arUrl = parse_url($rss_url);
    if (IntVal($arUrl["port"]) <= 0) {
        $arUrl["port"] = 80;
    }
    $ob = new CHTTP();
    $ob->http_timeout = 10;
    $ob->Query("GET", $arUrl["host"], $arUrl["port"], $arUrl["path"] . ($arUrl["query"] != '' ? "?" . $arUrl["query"] : ''), false, "", "N");
    $errno = $ob->errno;
    $errstr = $ob->errstr;
    $res = $ob->result;
    if (!$res) {
        $cache->EndDataCache(array("oRss" => false));
        return false;
    }
    if (preg_match("/<" . "\\?XML[^>]{1,}encoding=[\"']([^>\"']{1,})[\"'][^>]{0,}\\?" . ">/i", $res, $matches)) {
        $charset = Trim($matches[1]);
    }
    $res = $GLOBALS["APPLICATION"]->ConvertCharset($res, $charset, SITE_CHARSET);
    $xml = new CDataXML();
    $xml->LoadString($res);
    $oNode = $xml->SelectNodes("/rss/channel/title");
    if (!$oNode) {
        $cache->EndDataCache(array("oRss" => false));
        return false;
    }
    $oRssFeeds->title = $oNode->content;
    if (strlen(trim($oRssFeeds->title)) <= 0) {
        if ($oSubNode = $oNode->elementsByName("cdata-section")) {
            $oRssFeeds->title = $oSubNode[0]->content;
        }
    }
    if ($oNode = $xml->SelectNodes("/rss/channel/link")) {
        $oRssFeeds->link = $oNode->content;
    }
    if ($oNode = $xml->SelectNodes("/rss/channel/description")) {
        $oRssFeeds->description = $oNode->content;
    }
    if (strlen(trim($oRssFeeds->description)) <= 0) {
        if ($oNode && ($oSubNode = $oNode->elementsByName("cdata-section"))) {
            $oRssFeeds->description = $oSubNode[0]->content;
        }
    }
    if ($oNode = $xml->SelectNodes("/rss/channel/pubDate")) {
        $oRssFeeds->pubDate = $oNode->content;
    } elseif ($oNode = $xml->SelectNodes("/rss/channel/lastBuildDate")) {
        $oRssFeeds->pubDate = $oNode->content;
    }
    if ($oNode = $xml->SelectNodes("/rss/channel")) {
        $oNodes = $oNode->elementsByName("item");
        foreach ($oNodes as $oNode) {
            $item = array();
            if ($oSubNode = $oNode->elementsByName("title")) {
                $item["TITLE"] = $oSubNode[0]->content;
            }
            if (strlen(trim($item["TITLE"])) <= 0 && !empty($oSubNode)) {
                if ($oSubNode = $oSubNode[0]->elementsByName("cdata-section")) {
                    $item["TITLE"] = $oSubNode[0]->content;
                }
            }
            if ($oSubNode = $oNode->elementsByName("link")) {
                $item["LINK"] = $oSubNode[0]->content;
            }
            if ($oSubNode = $oNode->elementsByName("pubDate")) {
                $item["PUBDATE"] = $oSubNode[0]->content;
            }
            if ($oSubNode = $oNode->elementsByName("description")) {
                $item["DESCRIPTION"] = $oSubNode[0]->content;
            }
            if (strlen(trim($item["DESCRIPTION"])) <= 0 && !empty($oSubNode)) {
                if ($oSubNode = $oSubNode[0]->elementsByName("cdata-section")) {
                    $item["DESCRIPTION"] = $oSubNode[0]->content;
                }
            }
            if ($oSubNode = $oNode->elementsByName("author")) {
                $item["AUTHOR"] = $oSubNode[0]->content;
            }
            if (strlen(trim($item["AUTHOR"])) <= 0 && !empty($oSubNode)) {
                if ($oSubNode = $oSubNode[0]->elementsByName("cdata-section")) {
                    $item["AUTHOR"] = $oSubNode[0]->content;
                }
            }
            $oRssFeeds->items[] = $item;
        }
    }
    $cache->EndDataCache(array("oRss" => $oRssFeeds));
    return $oRssFeeds;
}
Ejemplo n.º 27
0
 function GetBoardFromSite($queryParameters)
 {
     global $APPLICATION;
     $result = array();
     $ob = new CHTTP();
     $ob->http_timeout = 60;
     $ob->Query("GET", "www.rossiya-airlines.com", 80, "/ru/passenger/about_flight/" . $queryParameters . '?ts=' . mktime(), false, "", "N");
     $result["ERROR"]["CODE"] = $ob->errno;
     $result["ERROR"]["MESSAGE"] = $ob->errstr;
     if (intval($result["ERROR"]["CODE"]) == 0) {
         $res = $ob->result;
         $res = str_replace('<table border="0" cellpadding="0" cellspacing="0" class="table" id="tblData">', "++++<table>", $res);
         $res = str_replace('$(document).ready(function()', "++++", $res);
         $explode = explode("++++", $res);
         $res = $explode[1];
         $res = substr($res, 0, strlen($res) - 22);
         $res = str_replace("<br>", " ", $res);
         $res = str_replace("<nobr>", "", $res);
         $res = str_replace("</nobr>", "", $res);
         //trace($res);
         $xml = new CDataXML();
         if ($xml->LoadString($res)) {
             $node = $xml->SelectNodes("/table");
             $rows = $node->elementsByName("tr");
             $akNames = array();
             $akCodes = array();
             $departures = array();
             $arrivals = array();
             $terminals = array();
             foreach ($rows as $row) {
                 if (strstr($row->getAttribute("class"), "finddata")) {
                     $cells = $row->elementsByName("td");
                     $flightNumber = $cells[0]->elementsByName("div");
                     // Определяем код авиакомпании и номер рейса
                     preg_match_all("/([A-Za-zА-Яа-я0-9]{2})([0-9]+)/", $flightNumber[0]->content, $flightNumber, PREG_PATTERN_ORDER);
                     $terminal = $cells[1]->elementsByName("div");
                     $city = $cells[2]->elementsByName("div");
                     $plannedTime = $cells[3]->elementsByName("div");
                     $actualTime = $cells[4]->elementsByName("div");
                     $status = $cells[5]->elementsByName("span");
                     $result["FLIGHTS"][] = array("FLIGHT" => array("AK_CODE" => $flightNumber[1][0], "NUMBER" => $flightNumber[2][0]), "AK_NAME" => "", "DEPARTURE" => htmlspecialcharsEx($city[0]->content), "ARRIVAL" => htmlspecialcharsEx($city[0]->content), "STATUS" => CAirportBoard::GetStatusInfo($status[0]->content), "TIME" => array("PLANNED" => CAirportBoard::GetDateTimeArray($plannedTime[0]->content), "ESTIMATED" => "", "ACTUAL" => CAirportBoard::GetDateTimeArray($actualTime[0]->content)), "TERMINAL" => htmlspecialchars($terminal[0]->content));
                     // Формируем список уникальных терминалов и пунктов вылета и прилета для фильтра
                     if (!in_array($flightNumber[1][0], $akCodes)) {
                         $akCodes[] = $flightNumber[1][0];
                     }
                     if (!in_array(htmlspecialcharsEx($city[0]->content), $departures)) {
                         $departures[] = htmlspecialcharsEx($city[0]->content);
                     }
                     if (!in_array(htmlspecialcharsEx($city[0]->content), $arrivals)) {
                         $arrivals[] = htmlspecialcharsEx($city[0]->content);
                     }
                     if (!in_array(htmlspecialcharsEx($terminal[0]->content), $terminals)) {
                         $terminals[] = htmlspecialcharsEx($terminal[0]->content);
                     }
                 }
             }
             sort($akNames);
             sort($akCodes);
             sort($departures);
             sort($arrivals);
             sort($terminals);
             $result["AK"] = $akNames;
             $result["AK_CODES"] = $akCodes;
             $result["DEPARTURES"] = $departures;
             $result["ARRIVALS"] = $arrivals;
             $result["TERMINALS"] = $terminals;
         }
     }
     //trace($result);
     return $result;
 }
Ejemplo n.º 28
0
 function encodeValue($name, $value, $complexDataTypeName = "")
 {
     global $xsd_simple_type;
     if (!is_array($this->outputVars) or !count($this->outputVars)) {
         CSOAPServer::ShowSOAPFault("encodeValue() has no Output Data Type Declaration for validation.");
         exit;
     }
     $dataType = "";
     $typeDeclaration = "";
     if (isset($this->outputVars[$name])) {
         $typeDeclaration = $this->outputVars[$name];
     } else {
         if (isset($this->typensVars[$name])) {
             $typeDeclaration = $this->typensVars[$name];
         } else {
             if (isset($this->typensVars[$complexDataTypeName][$name])) {
                 $typeDeclaration = $this->typensVars[$complexDataTypeName][$name];
             }
         }
     }
     if (isset($typeDeclaration["varType"])) {
         // if not, name = complex data type
         $dataType = $typeDeclaration["varType"];
     } else {
         $dataType = $name;
     }
     if (isset($xsd_simple_type[$dataType])) {
         $dataType = $xsd_simple_type[$dataType];
     }
     // Type validation
     $this->_validateType($dataType, $value);
     switch ($dataType) {
         case "string":
             $node = new CXMLCreator($name);
             //$node->setAttribute( "type", BX_SOAP_XSD_PREFIX . ":string" );
             $node->setData($value);
             return $node;
             break;
         case "boolean":
             $node = new CXMLCreator($name);
             //$node->setAttribute( "type", BX_SOAP_XSD_PREFIX . ":boolean" );
             if ($value === true) {
                 $node->setData("true");
             } else {
                 $node->setData("false");
             }
             return $node;
             break;
         case "integer":
             $node = new CXMLCreator($name);
             //$node->setAttribute( "type", BX_SOAP_XSD_PREFIX . ":int" );
             $node->setData(intval($value));
             return $node;
             break;
         case "float":
         case "double":
             $node = new CXMLCreator($name);
             //$node->setAttribute( "type", BX_SOAP_XSD_PREFIX . ":float" );
             $node->setData($value);
             return $node;
             break;
             // added by Sigurd
         // added by Sigurd
         case "base64":
         case "base64Binary":
             $node = new CXMLCreator($name);
             //$node->setAttribute("type", BX_SOAP_XSD_PREFIX . ":base64Binary" );
             $node->setData(base64_encode($value));
             return $node;
             break;
         case 'any':
             $node = new CXMLCreator($name);
             if (is_object($value)) {
                 // $fp = fopen($_SERVER['DOCUMENT_ROOT'].'/ws.log', 'a');
                 // fwrite($fp, $value->GetTree()."\n");
                 // fwrite($fp, '===================================='."\r\n");
                 // fclose($fp);
                 if (get_class($value) == 'CDataXML') {
                     $node->addChild(CXMLCreator::CreateFromDOM($value->GetTree()));
                 } elseif (get_class($value) == 'CDataXMLDocument') {
                     $node->addChild(CXMLCreator::CreateFromDOM($value));
                 } elseif (get_class($value) == 'CXMLCreator') {
                     $node->addChild($value);
                 }
             } else {
                 $data = new CDataXML();
                 if ($data->LoadString($value)) {
                     $node->addChild(CXMLCreator::CreateFromDOM($data->GetTree()));
                 } else {
                     $node->setData($value);
                 }
             }
             return $node;
             break;
         default:
             $node = new CXMLCreator($name);
             if (isset($typeDeclaration["arrType"])) {
                 if (!isset($typeDeclaration["varType"])) {
                     $this->_errorTypeValidation("varType [undef]", $value);
                 }
                 $varType = $typeDeclaration["varType"];
                 // Decode array
                 $maxOccurs = 0;
                 $arrayType = $typeDeclaration["arrType"];
                 if (isset($typeDeclaration["maxOccursA"])) {
                     $maxOccurs = $typeDeclaration["maxOccursA"];
                 }
                 if (isset($xsd_simple_type[$arrayType])) {
                     $i = 0;
                     $arrayType = $xsd_simple_type[$arrayType];
                     $arrayTypeEl = $varType . "El";
                     // TODO: non fixed. get El name from wsdl. or decl.
                     if (!is_array($value)) {
                         CSOAPCodec::_errorTypeValidation("Array", $value);
                     }
                     foreach ($value as $valnode) {
                         $i++;
                         $this->_validateType($arrayType, $valnode);
                         $cndata = new CXMLCreator($arrayTypeEl);
                         $cndata->setData($valnode);
                         $node->addChild($cndata);
                         if (intval($maxOccurs) > 0 and $i > $maxOccurs) {
                             break;
                         }
                     }
                 } else {
                     // Complex data type arrays // $arrayType as is.
                     // TODO: non fixed. get $arrayTypeEl name from wsdl. or decl.
                     $i = 0;
                     $arrayTypeEl = $varType . "El";
                     if (!is_array($value)) {
                         CSOAPCodec::_errorTypeValidation("Array", $value);
                     }
                     foreach ($value as $valnode) {
                         $decoded = null;
                         $i++;
                         $this->_validateType($arrayType, $valnode);
                         $decoded = $this->encodeValue($arrayType, $valnode);
                         $cndata = new CXMLCreator($arrayTypeEl);
                         if ($decoded) {
                             $this->_validateClassType("CXMLCreator", $decoded);
                             $decoded->setName($arrayTypeEl);
                             $node->addChild($decoded);
                         }
                         if (intval($maxOccurs) > 0 and $i > $maxOccurs) {
                             break;
                         }
                     }
                 }
             } else {
                 // Here we goes with struct, or with class
                 // First, try to find declaration
                 $objectDecl = 0;
                 $returnValue = array();
                 $params = array();
                 if (!isset($this->typensVars[$dataType])) {
                     break;
                 }
                 $objectDecl = $this->typensVars[$dataType];
                 if (!$objectDecl) {
                     CSOAPServer::ShowSOAPFault("encodeValue() cant find complex type declaration for {$dataType}.");
                     exit;
                 }
                 // Type of serialization: class/assoc array
                 $objectClass = null;
                 $serialize = "assoc";
                 if (isset($objectDecl["serialize"])) {
                     $serialize = $objectDecl["serialize"];
                     unset($objectDecl["serialize"]);
                 }
                 // Validate hard complex data types
                 if ($serialize == "assoc") {
                     $this->_validateType("array", $value);
                 }
                 if ($serialize != "assoc") {
                     $this->_validateClassType($dataType, $value);
                 }
                 foreach ($objectDecl as $pname => $param) {
                     $decoded = null;
                     $strict = true;
                     if (isset($param["strict"])) {
                         $strict = $param["strict"] == "strict" ? true : false;
                     }
                     if ($serialize == "assoc") {
                         //var_dump($pname); var_dump($value[$pname]); die();
                         if (isset($value[$pname])) {
                             $decoded = $this->encodeValue($pname, $value[$pname], $dataType);
                         }
                     } else {
                         if ($serialize != "assoc") {
                             if (isset($value->{$pname})) {
                                 $decoded = $this->encodeValue($pname, $value->{$pname}, $dataType);
                             }
                         }
                     }
                     if ($decoded) {
                         $this->_validateClassType("CXMLCreator", $decoded);
                     }
                     if (!$decoded and !$strict) {
                         CSOAPServer::ShowSOAPFault("Request has no enought params of strict type to be decoded. ");
                         exit;
                     }
                     $node->addChild($decoded);
                 }
             }
             return $node;
             break;
     }
     return false;
 }
     if (intval($errno) > 0 || strlen($errstr) > 0) {
         $strError = GetMessage("ERROR_QUERY_RATE");
     } else {
         $strError = GetMessage("ERROR_EMPTY_ANSWER");
     }
 } else {
     require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
     $charset = "windows-1251";
     if (preg_match("/<" . "\\?XML[^>]{1,}encoding=[\"']([^>\"']{1,})[\"'][^>]{0,}\\?" . ">/i", $strQueryText, $matches)) {
         $charset = trim($matches[1]);
     }
     $strQueryText = preg_replace("#<!DOCTYPE[^>]+?>#i", "", $strQueryText);
     $strQueryText = preg_replace("#<" . "\\?XML[^>]+?\\?" . ">#i", "", $strQueryText);
     $strQueryText = $APPLICATION->ConvertCharset($strQueryText, $charset, SITE_CHARSET);
     $objXML = new CDataXML();
     $res = $objXML->LoadString($strQueryText);
     if ($res !== false) {
         $arData = $objXML->GetArray();
     } else {
         $arData = false;
     }
     if ($currantCurrancy == "UAH") {
         //ukraina
         if (is_array($arData) && count($arData["ValCurs"]["#"]["Valute"]) > 0) {
             for ($j1 = 0, $intCount = count($arData["ValCurs"]["#"]["Valute"]); $j1 < $intCount; $j1++) {
                 if ($arData["ValCurs"]["#"]["Valute"][$j1]["#"]["CharCode"][0]["#"] == $CURRENCY) {
                     $RATE_CNT = IntVal($arData["ValCurs"]["#"]["Valute"][$j1]["#"]["Nominal"][0]["#"]);
                     $arCurrValue = str_replace(",", ".", $arData["ValCurs"]["#"]["Valute"][$j1]["#"]["Value"][0]["#"]);
                     $RATE = DoubleVal($arCurrValue);
                     break;
                 }
Ejemplo n.º 30
0
$assist_Shop_IDP = CSalePaySystemAction::GetParamValue("SHOP_IDP");
$assist_LOGIN = CSalePaySystemAction::GetParamValue("SHOP_LOGIN");
$assist_PASSWORD = CSalePaySystemAction::GetParamValue("SHOP_PASSWORD");
$password = CSalePaySystemAction::GetParamValue("SHOP_SECRET_WORLD");
$ORDER_ID = IntVal($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["ID"]);
set_time_limit(0);
$sHost = "payments.paysecure.ru";
$sUrl = "/orderstate/orderstate.cfm";
$dtm = AddToTimeStamp(array("MM" => -1), false);
$sVars = "Ordernumber=" . $ORDER_ID . "&Merchant_ID=" . $assist_Shop_IDP . "&login="******"&password="******"&FORMAT=3&StartYear=" . date('Y', $dtm) . "&StartMonth=" . date('n', $dtm) . "&StartYDay=" . date('j', $dtm) . "";
$aDesc = array("In Process" => array(GetMessage("SASP_IP"), GetMessage("SASPD_IP")), "Delayed" => array(GetMessage("SASP_D"), GetMessage("SASPD_D")), "Approved" => array(GetMessage("SASP_A"), GetMessage("SASPD_A")), "PartialApproved" => array(GetMessage("SASP_PA"), GetMessage("SASPD_PA")), "PartialDelayed" => array(GetMessage("SASP_PD"), GetMessage("SASPD_PD")), "Canceled" => array(GetMessage("SASP_C"), GetMessage("SASPD_C")), "PartialCanceled" => array(GetMessage("SASP_PC"), GetMessage("SASPD_PC")), "Declined" => array(GetMessage("SASP_DEC"), GetMessage("SASPD_DEC")), "Timeout" => array(GetMessage("SASP_T"), GetMessage("SASPD_T")));
$sResult = QueryGetData($sHost, 80, $sUrl, $sVars, $errno, $errstr, "POST");
if ($sResult != "") {
    require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/xml.php";
    $objXML = new CDataXML();
    $objXML->LoadString($sResult);
    $arResult = $objXML->GetArray();
    if (count($arResult) > 0 && $arResult["result"]["@"]["firstcode"] == "0") {
        $aRes = $arResult["result"]["#"]["order"][0]["#"];
        if (IntVal($aRes["ordernumber"][0]["#"]) == $ORDER_ID) {
            $arFields = array();
            $check = ToUpper(md5(toUpper(md5($password) . md5($assist_Shop_IDP . $aRes["ordernumber"][0]["#"] . $aRes["orderamount"][0]["#"] . $aRes["ordercurrency"][0]["#"] . $aRes["orderstate"][0]["#"]))));
            if ($aRes["checkvalue"][0]["#"] == $check) {
                $arOrder = CSaleOrder::GetByID($ORDER_ID);
                $arFields = array("PS_STATUS" => $aRes["orderstate"][0]["#"] == "Approved" ? "Y" : "N", "PS_STATUS_CODE" => substr($aRes["orderstate"][0]["#"], 0, 5), "PS_STATUS_DESCRIPTION" => $aDesc[$aRes["orderstate"][0]["#"]][0], "PS_STATUS_MESSAGE" => $aDesc[$aRes["orderstate"][0]["#"]][1], "PS_SUM" => DoubleVal($aRes["orderamount"][0]["#"]), "PS_CURRENCY" => $aRes["ordercurrency"][0]["#"], "PS_RESPONSE_DATE" => Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG))));
                if ($arOrder["PAYED"] != "Y" && CSalePaySystemAction::GetParamValue("AUTOPAY") == "Y" && $arFields["PS_STATUS"] == "Y" && Doubleval($arOrder["PRICE"]) == DoubleVal($arFields["PS_SUM"])) {
                    CSaleOrder::PayOrder($arOrder["ID"], "Y");
                }
            }
            if (!empty($arFields)) {
                CSaleOrder::Update($ORDER_ID, $arFields);