CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.3 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.3
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeRequest
  • CakeResponse
  • CakeSocket
  1: <?php
  2: /**
  3:  * Cake Socket connection class.
  4:  *
  5:  * PHP 5
  6:  *
  7:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9:  *
 10:  * Licensed under The MIT License
 11:  * For full copyright and license information, please see the LICENSE.txt
 12:  * Redistributions of files must retain the above copyright notice.
 13:  *
 14:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 15:  * @link          http://cakephp.org CakePHP(tm) Project
 16:  * @package       Cake.Network
 17:  * @since         CakePHP(tm) v 1.2.0
 18:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 19:  */
 20: 
 21: App::uses('Validation', 'Utility');
 22: 
 23: /**
 24:  * Cake network socket connection class.
 25:  *
 26:  * Core base class for network communication.
 27:  *
 28:  * @package       Cake.Network
 29:  */
 30: class CakeSocket {
 31: 
 32: /**
 33:  * Object description
 34:  *
 35:  * @var string
 36:  */
 37:     public $description = 'Remote DataSource Network Socket Interface';
 38: 
 39: /**
 40:  * Base configuration settings for the socket connection
 41:  *
 42:  * @var array
 43:  */
 44:     protected $_baseConfig = array(
 45:         'persistent' => false,
 46:         'host' => 'localhost',
 47:         'protocol' => 'tcp',
 48:         'port' => 80,
 49:         'timeout' => 30
 50:     );
 51: 
 52: /**
 53:  * Configuration settings for the socket connection
 54:  *
 55:  * @var array
 56:  */
 57:     public $config = array();
 58: 
 59: /**
 60:  * Reference to socket connection resource
 61:  *
 62:  * @var resource
 63:  */
 64:     public $connection = null;
 65: 
 66: /**
 67:  * This boolean contains the current state of the CakeSocket class
 68:  *
 69:  * @var boolean
 70:  */
 71:     public $connected = false;
 72: 
 73: /**
 74:  * This variable contains an array with the last error number (num) and string (str)
 75:  *
 76:  * @var array
 77:  */
 78:     public $lastError = array();
 79: 
 80: /**
 81:  * True if the socket stream is encrypted after a CakeSocket::enableCrypto() call
 82:  *
 83:  * @var boolean
 84:  */
 85:     public $encrypted = false;
 86: 
 87: /**
 88:  * Contains all the encryption methods available
 89:  *
 90:  * @var array
 91:  */
 92:     protected $_encryptMethods = array(
 93:         // @codingStandardsIgnoreStart
 94:         'sslv2_client' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT,
 95:         'sslv3_client' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
 96:         'sslv23_client' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
 97:         'tls_client' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
 98:         'sslv2_server' => STREAM_CRYPTO_METHOD_SSLv2_SERVER,
 99:         'sslv3_server' => STREAM_CRYPTO_METHOD_SSLv3_SERVER,
100:         'sslv23_server' => STREAM_CRYPTO_METHOD_SSLv23_SERVER,
101:         'tls_server' => STREAM_CRYPTO_METHOD_TLS_SERVER
102:         // @codingStandardsIgnoreEnd
103:     );
104: 
105: /**
106:  * Used to capture connection warnings which can happen when there are
107:  * SSL errors for example.
108:  *
109:  * @var array
110:  */
111:     protected $_connectionErrors = array();
112: 
113: /**
114:  * Constructor.
115:  *
116:  * @param array $config Socket configuration, which will be merged with the base configuration
117:  * @see CakeSocket::$_baseConfig
118:  */
119:     public function __construct($config = array()) {
120:         $this->config = array_merge($this->_baseConfig, $config);
121:         if (!is_numeric($this->config['protocol'])) {
122:             $this->config['protocol'] = getprotobyname($this->config['protocol']);
123:         }
124:     }
125: 
126: /**
127:  * Connect the socket to the given host and port.
128:  *
129:  * @return boolean Success
130:  * @throws SocketException
131:  */
132:     public function connect() {
133:         if ($this->connection) {
134:             $this->disconnect();
135:         }
136: 
137:         $scheme = null;
138:         if (isset($this->config['request']['uri']) && $this->config['request']['uri']['scheme'] === 'https') {
139:             $scheme = 'ssl://';
140:         }
141: 
142:         if (!empty($this->config['context'])) {
143:             $context = stream_context_create($this->config['context']);
144:         } else {
145:             $context = stream_context_create();
146:         }
147: 
148:         $connectAs = STREAM_CLIENT_CONNECT;
149:         if ($this->config['persistent']) {
150:             $connectAs |= STREAM_CLIENT_PERSISTENT;
151:         }
152: 
153:         set_error_handler(array($this, '_connectionErrorHandler'));
154:         $this->connection = stream_socket_client(
155:             $scheme . $this->config['host'] . ':' . $this->config['port'],
156:             $errNum,
157:             $errStr,
158:             $this->config['timeout'],
159:             $connectAs,
160:             $context
161:         );
162:         restore_error_handler();
163: 
164:         if (!empty($errNum) || !empty($errStr)) {
165:             $this->setLastError($errNum, $errStr);
166:             throw new SocketException($errStr, $errNum);
167:         }
168: 
169:         if (!$this->connection && $this->_connectionErrors) {
170:             $message = implode("\n", $this->_connectionErrors);
171:             throw new SocketException($message, E_WARNING);
172:         }
173: 
174:         $this->connected = is_resource($this->connection);
175:         if ($this->connected) {
176:             stream_set_timeout($this->connection, $this->config['timeout']);
177:         }
178:         return $this->connected;
179:     }
180: 
181: /**
182:  * socket_stream_client() does not populate errNum, or $errStr when there are
183:  * connection errors, as in the case of SSL verification failure.
184:  *
185:  * Instead we need to handle those errors manually.
186:  *
187:  * @param int $code
188:  * @param string $message
189:  * @return void
190:  */
191:     protected function _connectionErrorHandler($code, $message) {
192:         $this->_connectionErrors[] = $message;
193:     }
194: 
195: /**
196:  * Get the connection context.
197:  *
198:  * @return null|array Null when there is no connection, an array when there is.
199:  */
200:     public function context() {
201:         if (!$this->connection) {
202:             return;
203:         }
204:         return stream_context_get_options($this->connection);
205:     }
206: 
207: /**
208:  * Get the host name of the current connection.
209:  *
210:  * @return string Host name
211:  */
212:     public function host() {
213:         if (Validation::ip($this->config['host'])) {
214:             return gethostbyaddr($this->config['host']);
215:         }
216:         return gethostbyaddr($this->address());
217:     }
218: 
219: /**
220:  * Get the IP address of the current connection.
221:  *
222:  * @return string IP address
223:  */
224:     public function address() {
225:         if (Validation::ip($this->config['host'])) {
226:             return $this->config['host'];
227:         }
228:         return gethostbyname($this->config['host']);
229:     }
230: 
231: /**
232:  * Get all IP addresses associated with the current connection.
233:  *
234:  * @return array IP addresses
235:  */
236:     public function addresses() {
237:         if (Validation::ip($this->config['host'])) {
238:             return array($this->config['host']);
239:         }
240:         return gethostbynamel($this->config['host']);
241:     }
242: 
243: /**
244:  * Get the last error as a string.
245:  *
246:  * @return string Last error
247:  */
248:     public function lastError() {
249:         if (!empty($this->lastError)) {
250:             return $this->lastError['num'] . ': ' . $this->lastError['str'];
251:         }
252:         return null;
253:     }
254: 
255: /**
256:  * Set the last error.
257:  *
258:  * @param integer $errNum Error code
259:  * @param string $errStr Error string
260:  * @return void
261:  */
262:     public function setLastError($errNum, $errStr) {
263:         $this->lastError = array('num' => $errNum, 'str' => $errStr);
264:     }
265: 
266: /**
267:  * Write data to the socket.
268:  *
269:  * @param string $data The data to write to the socket
270:  * @return boolean Success
271:  */
272:     public function write($data) {
273:         if (!$this->connected) {
274:             if (!$this->connect()) {
275:                 return false;
276:             }
277:         }
278:         $totalBytes = strlen($data);
279:         for ($written = 0, $rv = 0; $written < $totalBytes; $written += $rv) {
280:             $rv = fwrite($this->connection, substr($data, $written));
281:             if ($rv === false || $rv === 0) {
282:                 return $written;
283:             }
284:         }
285:         return $written;
286:     }
287: 
288: /**
289:  * Read data from the socket. Returns false if no data is available or no connection could be
290:  * established.
291:  *
292:  * @param integer $length Optional buffer length to read; defaults to 1024
293:  * @return mixed Socket data
294:  */
295:     public function read($length = 1024) {
296:         if (!$this->connected) {
297:             if (!$this->connect()) {
298:                 return false;
299:             }
300:         }
301: 
302:         if (!feof($this->connection)) {
303:             $buffer = fread($this->connection, $length);
304:             $info = stream_get_meta_data($this->connection);
305:             if ($info['timed_out']) {
306:                 $this->setLastError(E_WARNING, __d('cake_dev', 'Connection timed out'));
307:                 return false;
308:             }
309:             return $buffer;
310:         }
311:         return false;
312:     }
313: 
314: /**
315:  * Disconnect the socket from the current connection.
316:  *
317:  * @return boolean Success
318:  */
319:     public function disconnect() {
320:         if (!is_resource($this->connection)) {
321:             $this->connected = false;
322:             return true;
323:         }
324:         $this->connected = !fclose($this->connection);
325: 
326:         if (!$this->connected) {
327:             $this->connection = null;
328:         }
329:         return !$this->connected;
330:     }
331: 
332: /**
333:  * Destructor, used to disconnect from current connection.
334:  *
335:  */
336:     public function __destruct() {
337:         $this->disconnect();
338:     }
339: 
340: /**
341:  * Resets the state of this Socket instance to it's initial state (before Object::__construct got executed)
342:  *
343:  * @param array $state Array with key and values to reset
344:  * @return boolean True on success
345:  */
346:     public function reset($state = null) {
347:         if (empty($state)) {
348:             static $initalState = array();
349:             if (empty($initalState)) {
350:                 $initalState = get_class_vars(__CLASS__);
351:             }
352:             $state = $initalState;
353:         }
354: 
355:         foreach ($state as $property => $value) {
356:             $this->{$property} = $value;
357:         }
358:         return true;
359:     }
360: 
361: /**
362:  * Encrypts current stream socket, using one of the defined encryption methods
363:  *
364:  * @param string $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
365:  * @param string $clientOrServer can be one of 'client', 'server'. Default is 'client'
366:  * @param boolean $enable enable or disable encryption. Default is true (enable)
367:  * @return boolean True on success
368:  * @throws InvalidArgumentException When an invalid encryption scheme is chosen.
369:  * @throws SocketException When attempting to enable SSL/TLS fails
370:  * @see stream_socket_enable_crypto
371:  */
372:     public function enableCrypto($type, $clientOrServer = 'client', $enable = true) {
373:         if (!array_key_exists($type . '_' . $clientOrServer, $this->_encryptMethods)) {
374:             throw new InvalidArgumentException(__d('cake_dev', 'Invalid encryption scheme chosen'));
375:         }
376:         $enableCryptoResult = false;
377:         try {
378:             $enableCryptoResult = stream_socket_enable_crypto($this->connection, $enable, $this->_encryptMethods[$type . '_' . $clientOrServer]);
379:         } catch (Exception $e) {
380:             $this->setLastError(null, $e->getMessage());
381:             throw new SocketException($e->getMessage());
382:         }
383:         if ($enableCryptoResult === true) {
384:             $this->encrypted = $enable;
385:             return true;
386:         }
387:         $errorMessage = __d('cake_dev', 'Unable to perform enableCrypto operation on CakeSocket');
388:         $this->setLastError(null, $errorMessage);
389:         throw new SocketException($errorMessage);
390:     }
391: 
392: }
393: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs