EGOCMS  24.0
EGOTEC Content-Managament-System
Ego_Http.php
gehe zur Dokumentation dieser Datei
1 <?php
2 
3 class Ego_Http {
4  private $_requestHeader = [];
5  public $responseHeader = [];
6  public $multiResponseHeader = [];
7  protected $info = [];
8  protected $multiInfo = [];
9  public $code = 0;
10  public $multiCode = [];
11  public $responseTime = 0;
12  public $multiResponseTime = [];
13  public $content = null;
14  public $multiContent = [];
15  public $cookie = [];
16  public $multiCookie = [];
17  public $error = null;
18  public $multiError = [];
19  public $verifySSL = true;
20  public $json = null;
21  public $multiJson = [];
22  public $returnHeader = true;
23  public $use_http_build_query = true;
24  public $flatten_array_params = false;
25  private $_proxy = [];
26 
30  public function __construct() {
31  $this->verifySSL = empty($GLOBALS['egotec_conf']['proxy']['insecure']);
32 
33  // Eingestellten Proxy verwenden
34  if ($GLOBALS['egotec_conf']['proxy']['proxy_host']) {
35  $this->proxy(
36  $GLOBALS['egotec_conf']['proxy']['proxy_host'],
37  $GLOBALS['egotec_conf']['proxy']['proxy_port'],
38  $GLOBALS['egotec_conf']['proxy']['proxy_ssl'],
39  $GLOBALS['egotec_conf']['proxy']['proxy_login'],
40  $GLOBALS['egotec_conf']['proxy']['proxy_password'],
41  (bool) $GLOBALS['egotec_conf']['proxy']['insecure']
42  );
43  }
44  }
45 
52  public function addHeader($headers) {
53  foreach ($headers as $key => $value) {
54  $this->_requestHeader[$key] = $value;
55  }
56  }
57 
65  public function auth($username, $password = '') {
66  $this->addHeader(array(
67  'Authorization' => 'Basic '.base64_encode("$username:$password")
68  ));
69  }
70 
82  public function proxy($host, $port, $ssl = false, $username = '', $password = '', $insecure = false) {
83  $this->_proxy['host'] = $host;
84  $this->_proxy['port'] = (int) $port;
85  $this->_proxy['ssl'] = (bool) $ssl;
86  $this->_proxy['username'] = $username;
87  $this->_proxy['password'] = $password;
88  $this->_proxy['insecure'] = $insecure;
89  }
90 
98  public function get($url, $additional_header = array(), int $timeout = 0) {
99  $this->request(array_merge([
100  'url' => $url,
101  'method' => 'GET',
102  'header' => $additional_header
103  ], $timeout > 0 ? ['timeout' => $timeout] : []));
104  }
105 
115  public function post($url, $param = array(), $additional_header = array(), $callback = null) {
116  $this->request(array(
117  'url' => $url,
118  'method' => 'POST',
119  'param' => $param,
120  'header' => $additional_header,
121  'callback' => $callback
122  ));
123  }
124 
132  public function delete($url, $additional_header = array()) {
133  $this->request(array(
134  'url' => $url,
135  'method' => 'DELETE',
136  'header' => $additional_header
137  ));
138  }
139 
148  public function put($url, $param = array(), $additional_header = array()) {
149  $this->request(array(
150  'url' => $url,
151  'method' => 'PUT',
152  'param' => $param,
153  'header' => $additional_header
154  ));
155  }
156 
166  public function download($url, $target, $param = array(), $additional_header = array()) {
167  $this->request(array(
168  'url' => $url,
169  'method' => 'POST',
170  'download' => $target,
171  'param' => $param,
172  'header' => $additional_header
173  ));
174  }
175 
185  public function upload($url, $file, $param = array(), $additional_header = array()) {
186  $this->request(array(
187  'url' => $url,
188  'method' => 'POST',
189  'upload' => $file,
190  'param' => $param,
191  'header' => $additional_header
192  ));
193  }
194 
202  public function multiRequest(array $requests): void {
203  $curlHandles = [];
204  $running = false;
205  $multiCurl = curl_multi_init();
206 
207  // Alle Curl-Aufrufe initialisieren
208  foreach ($requests as $request) {
209  $ch = $this->createCurlHandle($request);
210  curl_multi_add_handle($multiCurl, $ch);
211 
212  $curlHandles[] = $ch;
213  }
214 
215  // Alle cUrl-Aufrufe durchführen
216  do {
217  curl_multi_exec($multiCurl, $running);
218  curl_multi_select($multiCurl);
219  } while ($running > 0);
220 
221  foreach ($curlHandles as $ch) {
222  $response = curl_multi_getcontent($ch);
223 
224  if (!$response) {
225  $this->multiError[] = curl_error($ch);
226  } else {
227  $response_headers = [];
228  $response_cookies = [];
229  $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
230  $content_orig = substr($response, $header_size);
231  $headers = substr($response, 0, $header_size);
232 
233  // Headers sammeln
234  foreach (explode("\n", $headers) as $value) {
235  $pos = strpos($value, ':');
236  $response_headers[substr($value, 0, $pos)] = trim(substr($value, $pos + 1));
237  }
238 
239  $content = $response_headers['Content-Encoding'] == 'gzip' ? zlib_decode($content_orig) : $content_orig;
240 
241  // Cookies sammeln
242  if ($response_headers['Set-Cookie']) {
243  foreach (explode("\n", $response_headers['Set-Cookie']) as $line) {
244  $rows = explode(';', $line);
245  $row0_keyval = explode('=', array_shift($rows));
246  $cookie = ['value' => $row0_keyval[1]];
247 
248  foreach ($rows as $s) {
249  $keyval = explode('=', $s);
250  $cookie[trim($keyval[0])] = $keyval[1];
251  }
252 
253  $response_cookies[$row0_keyval[0]] = $cookie;
254  }
255  }
256 
257  $info = curl_getinfo($ch);
258 
259  $this->multiResponseHeader[] = $response_headers;
260  $this->multiCookie[] = $response_cookies;
261  $this->multiInfo[] = $info;
262  $this->multiResponseTime[] = $info['total_time'];
263  $this->multiCode[] = $info['http_code'];
264  $this->multiContent[] = $content;
265 
266  if (strpos($response_headers['Content-Type'], 'application/json') !== false) {
267  $this->multiJson[] = json_decode($content);
268  }
269  }
270 
271  curl_multi_remove_handle($multiCurl, $ch);
272  }
273 
274  curl_multi_close($multiCurl);
275  }
276 
283  public function request($request) {
284  $ch = $this->createCurlHandle($request);
285 
286  $response = curl_exec($ch);
287  if (!$response) {
288  $this->error = curl_error($ch);
289  return;
290  }
291  $this->error = null;
292 
293  if (!$request['download']) {
294  // Generate Response Headers
295  $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
296  $headers = substr($response, 0, $header_size);
297  $content_orig = substr($response, $header_size);
298  $this->responseHeader = array();
299  foreach (explode("\n", $headers) as $value) {
300  $pos = strpos($value, ":");
301  $key = substr($value, 0, $pos);
302  $val = trim(substr($value, $pos + 1));
303  $this->responseHeader[$key] = $val;
304  }
305 
306  // Collect Cookies
307  $this->cookie = array();
308  if ($this->responseHeader['Set-Cookie']) {
309  $cookies = explode("\n", $this->responseHeader['Set-Cookie']);
310  foreach ($cookies as $line) {
311  $row = explode(";", $line);
312  $row0 = array_shift($row);
313  $row0_keyval = explode("=", $row0);
314  $cookie = array('value' => $row0_keyval[1]);
315  foreach ($row as $s) {
316  $keyval = explode("=", $s);
317  $cookie[trim($keyval[0])] = $keyval[1];
318  }
319  $this->cookie[$row0_keyval[0]] = $cookie;
320  }
321  }
322  }
323 
324  $this->info = curl_getinfo($ch);
325  $this->responseTime = $this->info['total_time'];
326  $this->content = $this->responseHeader['Content-Encoding']=='gzip' ? zlib_decode($content_orig) : $content_orig;
327 
328  // decode JSON
329  if (
330  strpos($this->responseHeader['Content-Type'], "application/json") !== false
331  || strpos($this->responseHeader['content-type'], "application/json") !== false
332  ) {
333  $this->json = json_decode($this->content);
334  } else {
335  $this->json = null;
336  }
337 
338  $this->code = $this->info['http_code'];
339 
340  curl_close($ch);
341  if (isset($fp)) {
342  fclose($fp);
343  }
344  }
345 
349  private function createCurlHandle(array $request) {
350  $header = [];
351  foreach (array_merge($this->_requestHeader, $request['header'] ?? []) as $key => $value) {
352  $header[] = $key . ': ' . $value;
353  }
354 
355  $ch = curl_init();
356 
357  curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
358  curl_setopt($ch, CURLOPT_URL, $request['url']);
359  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request['method']);
360 
361  if ($request['timeout']) {
362  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request['timeout']);
363  curl_setopt($ch, CURLOPT_TIMEOUT, $request['timeout']);
364  }
365 
366  // Cookie
367  if ($request['cookie']) {
368  curl_setopt($ch, CURLOPT_COOKIE, $request['cookie']);
369  }
370 
371  // Download
372  if ($request['download']) {
373  $fp = fopen($request['download'], 'w+');
374  curl_setopt($ch, CURLOPT_FILE, $fp);
375  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
376  curl_setopt($ch, CURLOPT_TIMEOUT, 900);
377  } else {
378  curl_setopt($ch, CURLOPT_HEADER, $this->returnHeader);
379  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
380  }
381 
382  // Don't verify SSL certificates.
383  if (!$this->verifySSL) {
384  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
385  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
386  }
387 
388  // Upload
389  if ($request['upload']) {
390  curl_setopt($ch, CURLOPT_INFILE, $request['upload']);
391  curl_setopt($ch, CURLOPT_INFILESIZE, filesize($request['upload']));
392  }
393 
394  // URL Parameter
395  if (!empty($request['param'])) {
396  assert($request['method'] === 'POST', 'Makes only sense with POST.');
397  if ($this->use_http_build_query) {
398  if ($this->flatten_array_params) {
399  // Array Parameter mit numerischen Indizes flach darstellen (z.B. "x=1&x=2" anstatt "x[0]=1&x[1]=2")
400  $params = [];
401  $flatten = [];
402  foreach ($request['param'] as $key => $value) {
403  if (is_array($value) && count(array_filter(array_keys($value), 'is_string')) == 0) {
404  foreach ($value as $v) {
405  $flatten[] = "$key=" . rawurlencode($v);
406  }
407  } else {
408  $params[$key] = $value;
409  }
410  }
411 
412  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)
413  . (sizeof($flatten) > 0 ? '&' . implode('&', $flatten) : ''));
414  } else {
415  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request['param']));
416  }
417  } else {
418  curl_setopt($ch, CURLOPT_POSTFIELDS, $request['param']);
419  }
420  }
421 
422  // Proxy
423  if (!empty($this->_proxy)) {
424  curl_setopt($ch, CURLOPT_PROXY, $this->_proxy['host']);
425  curl_setopt($ch, CURLOPT_PROXYPORT, $this->_proxy['port']);
426  if ($this->_proxy['ssl']) {
427  curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
428  }
429  if (!empty($this->_proxy['username'])) {
430  curl_setopt($ch, CURLOPT_PROXYUSERPWD, implode(':', [
431  $this->_proxy['username'],
432  $this->_proxy['password']
433  ])
434  );
435  }
436  if ($this->_proxy['insecure']) {
437  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
438  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
439  }
440  }
441 
442  // Callback Funktion
443  if (!empty($request['callback']) && is_callable($request['callback'])) {
444  curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $str) use ($request) {
445  $request['callback']($str);
446  return strlen($str);
447  });
448  }
449 
450  return $ch;
451  }
452 }
__construct()
Definition: Ego_Http.php:30
$responseHeader
Definition: Ego_Http.php:5
$multiResponseHeader
Definition: Ego_Http.php:6
multiRequest(array $requests)
Definition: Ego_Http.php:202
$returnHeader
Definition: Ego_Http.php:22
$flatten_array_params
Definition: Ego_Http.php:24
auth($username, $password='')
Definition: Ego_Http.php:65
proxy($host, $port, $ssl=false, $username='', $password='', $insecure=false)
Definition: Ego_Http.php:82
$use_http_build_query
Definition: Ego_Http.php:23
$multiCookie
Definition: Ego_Http.php:16
$multiContent
Definition: Ego_Http.php:14
request($request)
Definition: Ego_Http.php:283
$responseTime
Definition: Ego_Http.php:11
post($url, $param=array(), $additional_header=array(), $callback=null)
Definition: Ego_Http.php:115
download($url, $target, $param=array(), $additional_header=array())
Definition: Ego_Http.php:166
upload($url, $file, $param=array(), $additional_header=array())
Definition: Ego_Http.php:185
$multiResponseTime
Definition: Ego_Http.php:12
addHeader($headers)
Definition: Ego_Http.php:52
$multiInfo
Definition: Ego_Http.php:8
put($url, $param=array(), $additional_header=array())
Definition: Ego_Http.php:148