1 <?php
 2 
 3 /**
 4  * Class for sockets over a proxy.
 5  *
 6  * @author gharlan
 7  *
 8  * @package redaxo\core
 9  */
10 class rex_socket_proxy extends rex_socket
11 {
12     protected $destinationHost;
13     protected $destinationPort;
14     protected $destinationSsl;
15 
16     /**
17      * Sets the destination.
18      *
19      * @param string $host Host name
20      * @param int    $port Port number
21      * @param bool   $ssl  SSL flag
22      *
23      * @return $this Current socket
24      */
25     public function setDestination($host, $port = 80, $ssl = false)
26     {
27         $this->destinationHost = $host;
28         $this->destinationPort = $port;
29         $this->destinationSsl = $ssl;
30 
31         $this->addHeader('Host', $host . ':' . $port);
32 
33         return $this;
34     }
35 
36     /**
37      * Sets the destination by a full URL.
38      *
39      * @param string $url Full URL
40      *
41      * @return $this Current socket
42      */
43     public function setDestinationUrl($url)
44     {
45         $parts = self::parseUrl($url);
46 
47         return $this->setDestination($parts['host'], $parts['port'], $parts['ssl'])->setPath($parts['path']);
48     }
49 
50     /**
51      * {@inheritdoc}
52      */
53     protected function openConnection()
54     {
55         parent::openConnection();
56 
57         if ($this->destinationSsl) {
58             $headers = [
59                 'Host' => $this->destinationHost . ':' . $this->destinationPort,
60                 'Proxy-Connection' => 'Keep-Alive',
61             ];
62             $response = $this->writeRequest('CONNECT', $this->destinationHost . ':' . $this->destinationPort, $headers);
63             if (!$response->isOk()) {
64                 throw new rex_socket_exception(sprintf('Couldn\'t connect to proxy server, server responds with "%s %s"', $response->getStatusCode(), $response->getStatusMessage()));
65             }
66             stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
67         } else {
68             unset($this->headers['Connection']);
69             $this->addHeader('Proxy-Connection', 'Close');
70             $this->path = 'http://' . $this->destinationHost . ':' . $this->destinationPort . $this->path;
71         }
72     }
73 }
74