1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
http.php
См. документацию.
1<?php
2
5
6class CHTTP
7{
8 var $url = '';
9 var $status = 0;
10 var $result = '';
11 var $fp = null;
12 var $headers = array();
13 var $cookies = array();
14 var $http_timeout = 30;
16 var $follow_redirect = false;
17 var $errno;
20
21 private $redirectMax = 5;
22 private $redirectsMade = 0;
23 private static $lastSetStatus = "";
24
25 public function __construct()
26 {
27 $defaultOptions = \Bitrix\Main\Config\Configuration::getValue("http_client_options");
28 if(isset($defaultOptions["socketTimeout"]))
29 {
30 $this->http_timeout = intval($defaultOptions["socketTimeout"]);
31 }
32
33 $this->user_agent = 'BitrixSM ' . __CLASS__ . ' class';
34 }
35
39 public static function URN2URI($urn, $server_name = '')
40 {
42 global $APPLICATION;
43
44 if(preg_match("/^[a-z]+:\\/\\//", $urn))
45 {
46 $uri = $urn;
47 }
48 else
49 {
50 if($APPLICATION->IsHTTPS())
51 $proto = "https://";
52 else
53 $proto = "http://";
54
55 if($server_name <> '')
56 $server_name = preg_replace("/:(443|80)$/", "", $server_name);
57 else
58 $server_name = preg_replace("/:(443|80)$/", "", $_SERVER["HTTP_HOST"]);
59
60 $uri = $proto.$server_name.$urn;
61 }
62 return $uri;
63 }
64
65 public function Download($url, $file)
66 {
67 if (is_resource($file))
68 {
69 $this->fp = $file;
70 }
71 else
72 {
73 CheckDirPath($file);
74 $this->fp = fopen($file, "wb");
75 }
76
77 if(is_resource($this->fp))
78 {
79 $res = $this->HTTPQuery('GET', $url);
80
81 if (!is_resource($file))
82 {
83 fclose($this->fp);
84 $this->fp = null;
85 }
86
87 return $res && ($this->status == 200);
88 }
89 return false;
90 }
91
95 public function Get($url)
96 {
97 if ($this->HTTPQuery('GET', $url))
98 {
99 return $this->result;
100 }
101 return false;
102 }
103
107 public function Post($url, $arPostData)
108 {
109 $postdata = static::PrepareData($arPostData);
110
111 if($this->HTTPQuery('POST', $url, $postdata))
112 {
113 return $this->result;
114 }
115 return false;
116 }
117
118 public static function PrepareData($arPostData, $prefix = '')
119 {
120 $str = '';
121
122 if(!is_array($arPostData))
123 {
124 $str = $arPostData;
125 }
126 else
127 {
128 foreach ($arPostData as $key => $value)
129 {
130 $name = $prefix == "" ? urlencode($key) : $prefix."[".urlencode($key)."]";
131
132 if(is_array($value))
133 {
134 $str .= static::PrepareData($value, $name);
135 }
136 else
137 {
138 $str .= '&'.$name.'='.urlencode($value);
139 }
140 }
141 }
142
143 if($prefix == '' && str_starts_with($str, '&'))
144 {
145 $str = substr($str, 1);
146 }
147
148 return $str;
149 }
150
154 public function HTTPQuery($method, $url, $postdata = '')
155 {
156 if(is_resource($this->fp))
157 $file_pos = ftell($this->fp);
158
159 $this->redirectsMade = 0;
160
161 while (true)
162 {
163 $this->url = $url;
164 $arUrl = $this->ParseURL($url);
165 if (!$this->Query($method, $arUrl['host'], $arUrl['port'], $arUrl['path_query'], $postdata, $arUrl['proto']))
166 {
167 return false;
168 }
169
170 if(
171 $this->follow_redirect
172 && isset($this->headers['Location'])
173 && $this->headers['Location'] <> ''
174 )
175 {
176 $url = $this->headers['Location'];
177 if($this->redirectsMade < $this->redirectMax)
178 {
179 //When writing to file we have to discard
180 //redirect body
181 if(is_resource($this->fp))
182 {
184 ftruncate($this->fp, $file_pos);
185 fseek($this->fp, $file_pos, SEEK_SET);
186 }
187 $this->redirectsMade++;
188 continue;
189 }
190 else
191 {
192 trigger_error("Maximum number of redirects (".$this->redirectMax.") has been reached at URL ".$url, E_USER_WARNING);
193 return false;
194 }
195 }
196 else
197 {
198 break;
199 }
200 }
201 return true;
202 }
203
207 public function Query($method, $host, $port, $path, $postdata = false, $proto = '', $post_content_type = 'N', $dont_wait_answer = false)
208 {
209 $this->status = 0;
210 $this->result = '';
211 $this->headers = array();
212 $this->cookies = array();
213 $fp = fsockopen($proto.$host, $port, $this->errno, $this->errstr, $this->http_timeout);
214 if ($fp)
215 {
216 $strRequest = "$method $path HTTP/1.0\r\n";
217 $strRequest .= "Connection: close\r\n";
218 $strRequest .= "User-Agent: {$this->user_agent}\r\n";
219 $strRequest .= "Accept: */*\r\n";
220 $strRequest .= "Host: $host\r\n";
221 $strRequest .= "Accept-Language: en\r\n";
222
223 foreach ($this->additional_headers as $key => $value)
224 $strRequest .= $key.": ".$value."\r\n";
225
226 if ($method == 'POST' || $method == 'PUT')
227 {
228 if ('N' !== $post_content_type)
229 $strRequest .= $post_content_type == '' ? '' : "Content-type: ".$post_content_type."\r\n";
230 else
231 $strRequest.= "Content-type: application/x-www-form-urlencoded\r\n";
232
233 if(!array_key_exists("Content-Length", $this->additional_headers))
234 $strRequest.= "Content-Length: ".strlen($postdata) . "\r\n";
235 }
236 $strRequest .= "\r\n";
237 fwrite($fp, $strRequest);
238
239 if ($method == 'POST' || $method == 'PUT')
240 {
241 if(is_resource($postdata))
242 {
243 while(!feof($postdata))
244 fwrite($fp, fread($postdata, 1024*1024));
245 }
246 else
247 {
248 fwrite($fp, $postdata);
249 }
250 }
251
252 if ($dont_wait_answer)
253 {
254 fclose($fp);
255 return true;
256 }
257
258 $headers = "";
259 while(!feof($fp))
260 {
261 $line = fgets($fp, 4096);
262 if($line == "\r\n" || $line === false)
263 {
264 //$line = fgets($fp, 4096);
265 break;
266 }
267 $headers .= $line;
268 }
269 $this->ParseHeaders($headers);
270
271 if(is_resource($this->fp))
272 {
273 while(!feof($fp))
274 {
275 $buf = fread($fp, 40960);
276 if ($buf === false)
277 break;
278 fwrite($this->fp, $buf);
279 fflush($this->fp);
280 }
281 }
282 else
283 {
284 $this->result = "";
285 while(!feof($fp))
286 {
287 $buf = fread($fp, 4096);
288 if ($buf === false)
289 break;
290 $this->result .= $buf;
291 }
292 }
293
294 fclose($fp);
295
296 return true;
297 }
298
300 global $APPLICATION;
301 $APPLICATION->ThrowException(
302 sprintf("Error connecting to %s:%s. Error code: \"%s\", error description: \"%s\"",
303 $this->errstr,
304 $this->errno,
305 $host,
306 $port
307 )
308 );
309 return false;
310 }
311
312 public function SetAuthBasic($user, $pass)
313 {
314 $this->additional_headers['Authorization'] = "Basic ".base64_encode($user.":".$pass);
315 }
316
320 public static function ParseURL($url)
321 {
322 $arUrl = parse_url($url);
323
324 $arUrl['proto'] = '';
325 if (array_key_exists('scheme', $arUrl))
326 {
327 $arUrl['scheme'] = mb_strtolower($arUrl['scheme']);
328 }
329 else
330 {
331 $arUrl['scheme'] = 'http';
332 }
333
334 if (!array_key_exists('port', $arUrl))
335 {
336 if ($arUrl['scheme'] == 'https')
337 {
338 $arUrl['port'] = 443;
339 }
340 else
341 {
342 $arUrl['port'] = 80;
343 }
344 }
345
346 if ($arUrl['scheme'] == 'https')
347 {
348 $arUrl['proto'] = 'ssl://';
349 }
350
351 $arUrl['path_query'] = array_key_exists('path', $arUrl) ? $arUrl['path'] : '/';
352 if (array_key_exists('query', $arUrl) && $arUrl['query'] <> '')
353 {
354 $arUrl['path_query'] .= '?' . $arUrl['query'];
355 }
356
357 return $arUrl;
358 }
359
360 public function ParseHeaders($strHeaders)
361 {
362 $arHeaders = explode("\n", $strHeaders);
363 foreach ($arHeaders as $k => $header)
364 {
365 if ($k == 0)
366 {
367 if (preg_match(',HTTP\S+ (\d+),', $header, $arFind))
368 {
369 $this->status = intval($arFind[1]);
370 }
371 }
372 elseif(str_contains($header, ':'))
373 {
374 $arHeader = explode(':', $header, 2);
375 if ($arHeader[0] == 'Set-Cookie')
376 {
377 if (($pos = mb_strpos($arHeader[1], ';')) !== false && $pos > 0)
378 {
379 $cookie = trim(mb_substr($arHeader[1], 0, $pos));
380 }
381 else
382 {
383 $cookie = trim($arHeader[1]);
384 }
385 $arCookie = explode('=', $cookie, 2);
386 $this->cookies[$arCookie[0]] = rawurldecode($arCookie[1]);
387 }
388 else
389 {
390 $this->headers[$arHeader[0]] = trim($arHeader[1]);
391 }
392 }
393 }
394 }
395
396 public function setFollowRedirect($follow)
397 {
398 $this->follow_redirect = $follow;
399 }
400
401 public function setRedirectMax($n)
402 {
403 $this->redirectMax = $n;
404 }
405
409 public static function sGet($url, $follow_redirect = false) //static get
410 {
411 $ob = new CHTTP();
412 $ob->setFollowRedirect($follow_redirect);
413 return $ob->Get($url);
414 }
415
419 public static function sPost($url, $arPostData, $follow_redirect = false) //static post
420 {
421 $ob = new CHTTP();
422 $ob->setFollowRedirect($follow_redirect);
423 return $ob->Post($url, $arPostData);
424 }
425
426 public function SetAdditionalHeaders($arHeader=array())
427 {
428 foreach($arHeader as $name => $value)
429 {
430 $name = str_replace(array("\r","\n"), "", $name);
431 $value = str_replace(array("\r","\n"), "", $value);
432 $this->additional_headers[$name] = $value;
433 }
434 }
435
444 public static function sGetHeader($url, $arHeader = array(), $httpTimeout = 0)
445 {
446 $httpTimeout = intval($httpTimeout);
447 $ob = new CHTTP();
448 if(!empty($arHeader))
449 $ob->SetAdditionalHeaders($arHeader);
450 if($httpTimeout > 0)
451 $ob->http_timeout = $httpTimeout;
452
453 return $ob->Get($url);
454 }
455
465 public static function sPostHeader($url, $arPostData, $arHeader = array(), $http_timeout = 0)
466 {
468 $ob = new CHTTP();
469 if(!empty($arHeader))
470 $ob->SetAdditionalHeaders($arHeader);
471 if($http_timeout > 0)
472 $ob->http_timeout = $http_timeout;
473 return $ob->Post($url, $arPostData);
474 }
475
476 public static function SetStatus($status)
477 {
478 $bCgi = (stristr(php_sapi_name(), "cgi") !== false);
479 if($bCgi && (!defined("BX_HTTP_STATUS") || BX_HTTP_STATUS == false))
480 header("Status: ".$status);
481 else
482 header($_SERVER["SERVER_PROTOCOL"]." ".$status);
483 self::$lastSetStatus = $status;
484 }
485
486 public static function GetLastStatus()
487 {
488 return self::$lastSetStatus;
489 }
490
491 public static function SetAuthHeader($bDigestEnabled=true)
492 {
493 self::SetStatus('401 Unauthorized');
494
495 if(defined('BX_HTTP_AUTH_REALM'))
496 $realm = BX_HTTP_AUTH_REALM;
497 else
498 $realm = "Bitrix Site Manager";
499
500 header('WWW-Authenticate: Basic realm="'.$realm.'"');
501
502 if($bDigestEnabled !== false && COption::GetOptionString("main", "use_digest_auth", "N") == "Y")
503 {
504 // On first try we found that we don't know user digest hash. Let ask only Basic auth first.
505 if(\Bitrix\Main\Application::getInstance()->getKernelSession()->get("BX_HTTP_DIGEST_ABSENT") !== true)
506 header('WWW-Authenticate: Digest realm="'.$realm.'", nonce="'.uniqid().'"');
507 }
508 }
509
510 /*
511 * @deprecated Use \Bitrix\Main\Server::parseAuthRequest()
512 */
513 public static function ParseAuthRequest()
514 {
515 return Main\Context::getCurrent()->getServer()->parseAuthRequest();
516 }
517
521 public static function urlAddParams($url, $add_params, $options = [])
522 {
523 if (!empty($add_params))
524 {
525 $params = [];
526 foreach ($add_params as $name => $value)
527 {
528 if (is_array($value))
529 {
530 // arrays are unsupported, use \Bitrix\Main\Web\Uri::addParams()
531 continue;
532 }
533 if (!empty($options["skip_empty"]) && (string)$value == '')
534 {
535 continue;
536 }
537 if (!empty($options["encode"]))
538 {
539 $params[] = urlencode($name) . '=' . urlencode($value);
540 }
541 else
542 {
543 $params[] = $name . '=' . $value;
544 }
545 }
546
547 if (!empty($params))
548 {
549 $ch = (mb_strpos($url, "?") === false ? "?" : "&");
550
551 $p2 = mb_strpos($url, "#");
552 if ($p2 === false)
553 {
554 $url = $url . $ch . implode("&", $params);
555 }
556 else
557 {
558 $url = mb_substr($url, 0, $p2) . $ch . implode("&", $params) . mb_substr($url, $p2);
559 }
560 }
561 }
562 return $url;
563 }
564
568 public static function urlDeleteParams($url, $delete_params, $options = array())
569 {
570 $url_parts = explode("?", $url, 2);
571 if(count($url_parts) == 2 && $url_parts[1] <> '')
572 {
573 if(($options["delete_system_params"] ?? false))
574 $delete_params = array_merge($delete_params, \Bitrix\Main\HttpRequest::getSystemParameters());
575
576 $params_pairs = explode("&", $url_parts[1]);
577 foreach($params_pairs as $i => $param_pair)
578 {
579 $name_value_pair = explode("=", $param_pair, 2);
580 if(count($name_value_pair) == 2 && in_array($name_value_pair[0], $delete_params))
581 unset($params_pairs[$i]);
582 }
583
584 if(empty($params_pairs))
585 return $url_parts[0];
586 else
587 return $url_parts[0]."?".implode("&", $params_pairs);
588 }
589
590 return $url;
591 }
592
596 public static function urnEncode($str, $charset = false)
597 {
598 return Web\Uri::urnEncode($str, $charset);
599 }
600
604 public static function urnDecode($str, $charset = false)
605 {
606 return Web\Uri::urnDecode($str, $charset);
607 }
608
612 public static function isPathTraversalUri($url)
613 {
614 $uri = new Web\Uri($url);
615 return $uri->isPathTraversal();
616 }
617}
$path
Определения access_edit.php:21
global $APPLICATION
Определения include.php:80
static getInstance()
Определения application.php:98
static getValue($name)
Определения configuration.php:24
static getSystemParameters()
Определения httprequest.php:520
Определения uri.php:17
static urnDecode($str, $charset=false)
Определения uri.php:445
static urnEncode($str, $charset='UTF-8')
Определения uri.php:416
Определения http.php:7
static sGetHeader($url, $arHeader=array(), $httpTimeout=0)
Определения http.php:444
__construct()
Определения http.php:25
setRedirectMax($n)
Определения http.php:401
$follow_redirect
Определения http.php:16
static SetStatus($status)
Определения http.php:476
$result
Определения http.php:10
HTTPQuery($method, $url, $postdata='')
Определения http.php:154
$errstr
Определения http.php:18
setFollowRedirect($follow)
Определения http.php:396
Post($url, $arPostData)
Определения http.php:107
$fp
Определения http.php:11
static sGet($url, $follow_redirect=false)
Определения http.php:409
$errno
Определения http.php:17
static urlDeleteParams($url, $delete_params, $options=array())
Определения http.php:568
static PrepareData($arPostData, $prefix='')
Определения http.php:118
$http_timeout
Определения http.php:14
SetAdditionalHeaders($arHeader=array())
Определения http.php:426
static GetLastStatus()
Определения http.php:486
static SetAuthHeader($bDigestEnabled=true)
Определения http.php:491
$headers
Определения http.php:12
Query($method, $host, $port, $path, $postdata=false, $proto='', $post_content_type='N', $dont_wait_answer=false)
Определения http.php:207
$status
Определения http.php:9
static urnDecode($str, $charset=false)
Определения http.php:604
ParseHeaders($strHeaders)
Определения http.php:360
Get($url)
Определения http.php:95
static ParseAuthRequest()
Определения http.php:513
static sPostHeader($url, $arPostData, $arHeader=array(), $http_timeout=0)
Определения http.php:465
Download($url, $file)
Определения http.php:65
static sPost($url, $arPostData, $follow_redirect=false)
Определения http.php:419
static URN2URI($urn, $server_name='')
Определения http.php:39
static isPathTraversalUri($url)
Определения http.php:612
static urnEncode($str, $charset=false)
Определения http.php:596
static urlAddParams($url, $add_params, $options=[])
Определения http.php:521
$url
Определения http.php:8
static ParseURL($url)
Определения http.php:320
$user_agent
Определения http.php:15
$cookies
Определения http.php:13
$additional_headers
Определения http.php:19
SetAuthBasic($user, $pass)
Определения http.php:312
$options
Определения commerceml2.php:49
$str
Определения commerceml2.php:63
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
else $ch
Определения group_list_element_edit.php:27
$_SERVER["DOCUMENT_ROOT"]
Определения cron_frame.php:9
if(file_exists($_SERVER['DOCUMENT_ROOT'] . "/urlrewrite.php")) $uri
Определения urlrewrite.php:61
CheckDirPath($path)
Определения tools.php:2707
$name
Определения menu_edit.php:35
Определения cookie.php:3
$user
Определения mysql_to_pgsql.php:33
$host
Определения mysql_to_pgsql.php:32
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
$i
Определения factura.php:643
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$pass
Определения result.php:5
$method
Определения index.php:27
$k
Определения template_pdf.php:567
$n
Определения update_log.php:107