/** * Authenticates against the given parameters * * $options requires the following key-value pairs: * * 'filename' => path to digest authentication file * 'realm' => digest authentication realm * 'username' => digest authentication user * 'password' => password for the user of the realm * * @param array $options * @throws Zend_Auth_Digest_Exception * @return Zend_Auth_Digest_Token */ public static function staticAuthenticate(array $options) { $optionsRequired = array('filename', 'realm', 'username', 'password'); foreach ($optionsRequired as $optionRequired) { if (!isset($options[$optionRequired]) || !is_string($options[$optionRequired])) { throw Zend::exception('Zend_Auth_Digest_Exception', "Option '{$optionRequired}' is required to be " . 'provided as a string'); } } if (false === ($fileHandle = @fopen($options['filename'], 'r'))) { throw Zend::exception('Zend_Auth_Digest_Exception', "Cannot open '{$options['filename']}' for reading"); } require_once 'Zend/Auth/Digest/Token.php'; $id = "{$options['username']}:{$options['realm']}"; $idLength = strlen($id); $tokenValid = false; $tokenIdentity = array('realm' => $options['realm'], 'username' => $options['username']); while ($line = trim(fgets($fileHandle))) { if (substr($line, 0, $idLength) === $id) { if (substr($line, -32) === md5("{$options['username']}:{$options['realm']}:{$options['password']}")) { $tokenValid = true; $tokenMessage = null; } else { $tokenMessage = 'Password incorrect'; } return new Zend_Auth_Digest_Token($tokenValid, $tokenIdentity, $tokenMessage); } } $tokenMessage = "Username '{$options['username']}' and realm '{$options['realm']}' combination not found"; return new Zend_Auth_Digest_Token($tokenValid, $tokenIdentity, $tokenMessage); }
/** * Disconnects from the peer, closes the socket. * * @return void */ protected function _disconnect() { if (!is_resource($this->_socket)) { throw Zend::exception('Zend_TimeSync_ProtocolException', "could not close server connection from '{$this->_timeserver}' on port '{$this->_port}'"); } @fclose($this->_socket); $this->_socket = null; }
/** * @param string $var * @param string $value */ protected function __set($var, $value) { switch ($var) { case 'updatedMin': case 'updatedMax': throw Zend::exception('Zend_Gdata_Exception', "Parameter '{$var}' is not currently supported in Spreadsheets."); break; } parent::__set($var, $value); }
public function testException() { $this->assertTrue(Zend::exception('Zend_Exception') instanceof Exception); try { $e = Zend::exception('Zend_FooBar_Baz', 'should fail'); $this->fail('invalid exception class should throw exception'); } catch (Exception $e) { // success... } }
/** * Sets a new timestamp * * @param $date mixed - OPTIONAL timestamp otherwise actual timestamp is used * @return boolean * @throws Zend_Date_Exception */ public function setTimestamp($date = false) { // no date value, take actual time if ($date === false) { $this->_unixtimestamp = time(); return true; } if (is_numeric($date)) { $this->_unixtimestamp = $date; return true; } throw Zend::exception('Zend_Date_Exception', '\'' . $date . '\' is no valid date'); }
/** * Create instance with parameters * Disallowed parameters are: * - filename use Zend_Mail_Mbox for a single file * Supported parameters are: * - rootdir rootdir of mbox structure * - folder intial selected folder, default is 'INBOX' * * @param $params array mail reader specific parameters * @throws Zend_Mail_Exception */ public function __construct($params) { if (isset($params['filename'])) { throw Zend::exception('Zend_Mail_Exception', 'use Zend_Mail_Mbox for a single file'); } if (!isset($params['rootdir']) || !is_dir($params['rootdir'])) { throw Zend::exception('Zend_Mail_Exception', 'no valid rootdir given in params'); } $this->_rootdir = rtrim($params['rootdir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->_buildFolderTree($this->_rootdir); $this->selectFolder(!empty($params['folder']) ? $params['folder'] : 'INBOX'); $this->_has['top'] = true; }
/** * Create instance with parameters * Supported parameters are: * - rootdir rootdir of maildir structure * - dirname alias for rootdir * - delim delim char for folder structur, default is '.' * - folder intial selected folder, default is 'INBOX' * * @param $params array mail reader specific parameters * @throws Zend_Mail_Exception */ public function __construct($params) { if (isset($params['dirname']) && !isset($params['rootdir'])) { $params['rootdir'] = $params['dirname']; } if (!isset($params['rootdir']) || !is_dir($params['rootdir'])) { throw Zend::exception('Zend_Mail_Exception', 'no valid rootdir given in params'); } $this->_rootdir = rtrim($params['rootdir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $this->_delim = isset($params['delim']) ? $params['delim'] : '.'; $this->_buildFolderTree(); $this->selectFolder(!empty($params['folder']) ? $params['folder'] : 'INBOX'); $this->_has['top'] = true; }
/** * Writes/receives data to/from the timeserver * * @return int unix timestamp */ protected function _query() { $this->_connect(); $begin = time(); fputs($this->_socket, "\n"); $result = fread($this->_socket, 49); $end = time(); $this->_disconnect(); if (!$result) { throw Zend::exception('Zend_TimeSync_ProtocolException', 'invalid result returned from server'); } else { $time = abs(hexdec('7fffffff') - hexdec(bin2hex($result)) - hexdec('7fffffff')); $time -= 2208988800; // socket delay $time -= ($end - $begin) / 2; return $time; } }
/** * fetch one or more items of one or more messages * * @param string|array $items items to fetch from message(s) as string (if only one item) * or array of strings * @param int $from message for items or start message if $to !== null * @param int|null $to if null only one message ($from) is fetched, else it's the * last message, INF means last message avaible * @return string|array if only one item of one message is fetched it's returned as string * if items of one message are fetched it's returned as (name => value) * if one items of messages are fetched it's returned as (msgno => value) * if items of messages are fetchted it's returned as (msgno => (name => value)) */ public function fetch($items, $from, $to = null) { if ($to === null) { $set = (int) $from; } else { if (is_array($from)) { $set = implode(',', $from); } else { if ($to === INF) { $set = (int) $from . ':*'; } else { $set = (int) $from . ':' . (int) $to; } } } $items = (array) $items; $itemList = $this->escapeList($items); $this->sendRequest('FETCH', array($set, $itemList), $tag); $result = array(); while (!$this->readLine($tokens, $tag)) { if ($tokens[1] != 'FETCH') { continue; } if ($to === null && $tokens[0] != $from) { continue; } if (count($items) == 1) { $data = next($tokens[2]); } else { $data = array(); while (key($tokens[2]) !== null) { $data[current($tokens[2])] = next($tokens[2]); next($tokens[2]); } } if ($to === null && $tokens[0] == $from) { return $data; } $result[$tokens[0]] = $data; } if ($to === null) { throw Zend::exception('Zend_Mail_Transport_Exception', 'the single id was not found in response'); } return $result; }
/** * Set a new type, and convert the value * * @param $type new type to set * @throws Zend_Measure_Exception */ public function setType($type) { if (empty(self::$_UNITS[$type])) { throw Zend::exception('Zend_Measure_Exception', 'unknown type of torque:' . $type); } // Convert to standard value $value = parent::getValue(); if (is_array(self::$_UNITS[parent::getType()][0])) { foreach (self::$_UNITS[parent::getType()][0] as $key => $found) { switch ($key) { case "/": $value /= $found; break; default: $value *= $found; break; } } } else { $value = $value * self::$_UNITS[parent::getType()][0]; } // Convert to expected value if (is_array(self::$_UNITS[$type][0])) { foreach (self::$_UNITS[$type][0] as $key => $found) { switch ($key) { case "/": $value *= $found; break; default: $value /= $found; break; } } } else { $value = $value / self::$_UNITS[$type][0]; } parent::setValue($value, $type, $this->_Locale); parent::setType($type); }
/** * Set a new type, and convert the value * * @throws Zend_Measure_Exception */ public function setType($type) { if (empty(self::$_UNITS[$type])) { throw Zend::exception('Zend_Measure_Exception', 'unknown type of force:' . $type); } // Convert to standard value $value = parent::getValue(); $value = $value * self::$_UNITS[parent::getType()][0]; // Convert to expected value $value = $value / self::$_UNITS[$type][0]; parent::setValue($value, $type, $this->_Locale); parent::setType($type); }
/** * * create instance with parameters * Supported paramters are * - host hostname or ip address of IMAP server * - user username * - password password for user 'username' [optional, default = ''] * - port port for IMAP server [optional, default = 110] * - ssl 'SSL' or 'TLS' for secure sockets * - folder select this folder [optional, default = 'INBOX'] * * @param $params array mail reader specific parameters * @throws Zend_Mail_Exception */ public function __construct($params) { if ($params instanceof Zend_Mail_Transport_Imap) { $this->_protocol = $params; $this->_currentFolder = 'INBOX'; if (!$this->_protocol->select($this->_currentFolder)) { throw Zend::exception('Zend_Mail_Exception', 'cannot select INBOX, is this a valid transport?'); } return; } if (!isset($params['host']) || !isset($params['user'])) { throw Zend::exception('Zend_Mail_Exception', 'need at least a host an user in params'); } $params['password'] = isset($params['password']) ? $params['password'] : ''; $params['port'] = isset($params['port']) ? $params['port'] : null; $params['ssl'] = isset($params['ssl']) ? $params['ssl'] : false; $this->_protocol = new Zend_Mail_Transport_Imap(); $this->_protocol->connect($params['host'], $params['port'], $params['ssl']); if (!$this->_protocol->login($params['user'], $params['password'])) { throw Zend::exception('Zend_Mail_Exception', 'cannot login, user or password wrong'); } $this->_currentFolder = isset($params['folder']) ? $params['folder'] : 'INBOX'; if (!$this->_protocol->select($this->_currentFolder)) { throw Zend::exception('Zend_Mail_Exception', 'cannot change folder, maybe it does not exist'); } }
/** * Unregister a plugin. * * @param Zend_Controller_Plugin_Abstract $plugin * @return Zend_Controller_Plugin_Broker */ public function unregisterPlugin(Zend_Controller_Plugin_Abstract $plugin) { $key = array_search($plugin, $this->_plugins, true); if (false === $key) { throw Zend::exception('Zend_Controller_Exception', 'Plugin never registered.'); } unset($this->_plugins[$key]); return $this; }
/** * Send the given string followed by a LINEEND to the server * * @param string $str * @throws Zend_Mail_Transport_Exception */ protected function _send($str) { $res = fwrite($this->_con, $str . $this->EOL); if ($res === false) { throw Zend::exception('Zend_Mail_Transport_Exception', 'Could not write to SMTP server'); } if (self::DEBUG) { echo "S: {$str}<br>\n"; } }
/** * stub for not supported message deletion */ public function removeMessage($id) { throw Zend::exception('Zend_Mail_Exception', 'maildir is (currently) read-only'); }
/** * @param string $var * @param string $value */ protected function __set($var, $value) { switch ($var) { case 'query': case 'q': $var = 'q'; throw Zend::exception('Zend_Gdata_Exception', 'Text queries are not currently supported in Blogger.'); break; case 'publishedMin': $var = 'published-min'; $value = $this->formatTimestamp($value); break; case 'publishedMax': $var = 'published-max'; $value = $this->formatTimestamp($value); break; case 'blogName': $var = '_blogName'; break; case 'category': $var = '_category'; throw Zend::exception('Zend_Gdata_Exception', 'Category queries are not currently supported in Blogger.'); break; case 'entry': $var = '_entry'; throw Zend::exception('Zend_Gdata_Exception', 'Entry queries are not currently supported in Blogger.'); break; default: break; } parent::__set($var, $value); }
/** * Get controller name * * Try request first; if not found, try pulling from request parameter; * if still not found, fallback to default * * @param Zend_Controller_Request_Abstract $request * @param array $directories * @return string|false Returns class name on success */ protected function _getController($request, $directories = null) { if (null === $directories) { $directories = $this->getControllerDirectory(); } if (empty($directories)) { throw Zend::exception('Zend_Controller_Dispatcher_Exception', 'Controller directory never set. Use setControllerDirectory() first'); } $controllerName = $request->getControllerName(); if (empty($controllerName)) { $controllerName = $this->getDefaultController(); $request->setControllerName($controllerName); } $className = $this->formatControllerName($controllerName); /** * Determine if controller is dispatchable * * Checks to see if a module name is present in the request; if so, * checks for class file existing in module directory. Otherwise, loops through * directories in FIFO order to find it. */ $dispatchable = false; $module = (string) $request->getParam('module', false); if ($module && isset($directories[$module])) { $dispatchable = Zend::isReadable($directories[$module] . DIRECTORY_SEPARATOR . $className . '.php'); if ($dispatchable) { $this->_curDirectory = $directories[$module]; } } else { foreach ($directories as $directory) { $dispatchable = Zend::isReadable($directory . DIRECTORY_SEPARATOR . $className . '.php'); if ($dispatchable) { $this->_curDirectory = $directory; break; } } } return $dispatchable ? $className : false; }
/** * Route a request * * Routes requests of the format /controller/action by default (action may * be omitted). Additional parameters may be specified as key/value pairs * separated by the directory separator: * /controller/action/key/value/key/value. * * To specify a module to use (basically, subdirectory) when routing the * request, set the 'useModules' parameter via the front controller or * {@link setParam()}: $router->setParam('useModules', true) * * @param Zend_Controller_Request_Abstract $request * @return void */ public function route(Zend_Controller_Request_Abstract $request) { if (!$request instanceof Zend_Controller_Request_Http) { throw Zend::exception('Zend_Controller_Router_Exception', 'Zend_Controller_Router requires a Zend_Controller_Request_Http-based request object'); } $pathInfo = $request->getPathInfo(); $pathSegs = explode('/', trim($pathInfo, '/')); /** * Retrieve module if useModules is set in object */ $useModules = $this->getParam('useModules'); if (!empty($useModules)) { if (isset($pathSegs[0]) && !empty($pathSegs[0])) { $module = array_shift($pathSegs); } } /** * Get controller and action from request * Attempt to get from path_info; controller is first item, action * second */ if (isset($pathSegs[0]) && !empty($pathSegs[0])) { $controller = array_shift($pathSegs); } if (isset($pathSegs[0]) && !empty($pathSegs[0])) { $action = array_shift($pathSegs); } /** * Any optional parameters after the action are stored in * an array of key/value pairs: * * http://www.zend.com/controller-name/action-name/param-1/3/param-2/7 * * $params = array(2) { * ["param-1"]=> string(1) "3" * ["param-2"]=> string(1) "7" * } */ $params = array(); $segs = count($pathSegs); if (0 < $segs) { for ($i = 0; $i < $segs; $i = $i + 2) { $key = urldecode($pathSegs[$i]); $value = isset($pathSegs[$i + 1]) ? urldecode($pathSegs[$i + 1]) : null; $params[$key] = $value; } } $request->setParams($params); /** * Set module, controller and action, now that params are set */ if (isset($module)) { $request->setParam('module', urldecode($module)); } if (isset($controller)) { $request->setControllerName(urldecode($controller)); } if (isset($action)) { $request->setActionName(urldecode($action)); } return $request; }
/** * Set Google authentication credentials. * Must be done before trying to do any Google Data operations that * require authentication. * For example, viewing private data, or posting or deleting entries. * * @param string $email * @param string $password * @param string $service * @param Zend_Http_Client $client * @param string $source * @return Zend_Http_Client */ public function getHttpClient($email, $password, $service = 'xapi', $client = null, $source = self::DEFAULT_SOURCE) { if (!($email && $password)) { throw Zend::exception('Zend_Http_Exception', 'Please set your Google credentials before trying to authenticate'); } if ($client == null) { $client = new Zend_Http_Client(); } if (!$client instanceof Zend_Http_Client) { throw Zend::exception('Zend_Http_Exception', 'Client is not an instance of Zend_Http_Client.'); } // Build the HTTP client for authentication $client->setUri(self::CLIENTLOGIN_URI); $client->setConfig(array('maxredirects' => 0, 'strictredirects' => true)); $client->setParameterPost('accountType', 'HOSTED_OR_GOOGLE'); $client->setParameterPost('Email', (string) $email); $client->setParameterPost('Passwd', (string) $password); $client->setParameterPost('service', (string) $service); $client->setParameterPost('source', (string) $source); // Send the authentication request // For some reason Google's server causes an SSL error. We use the // output buffer to supress an error from being shown. Ugly - but works! ob_start(); $response = $client->request('POST'); ob_end_clean(); // Parse Google's response $goog_resp = array(); foreach (explode("\n", $response->getBody()) as $l) { $l = chop($l); if ($l) { list($key, $val) = explode('=', chop($l), 2); $goog_resp[$key] = $val; } } if ($response->getStatus() == 200) { $headers['authorization'] = 'GoogleLogin auth=' . $goog_resp['Auth']; $client = new Zend_Http_Client(); $client->setHeaders($headers); return $client; } elseif ($response->getStatus() == 403) { throw Zend::exception('Zend_Http_Exception', 'Authentication with Google failed. Reason: ' . (isset($goog_resp['Error']) ? $goog_resp['Error'] : 'Unspecified.')); } }
/** * Set values * * In order to follow {@link __get()}, which operates on a number of * superglobals, setting values through overloading is not allowed and will * raise an exception. Use setParam() instead. * * @param string $key * @param mixed $value * @return void * @throws Zend_Controller_Request_Exception */ public function __set($key, $value) { throw Zend::exception('Zend_Controller_Request_Exception', 'Setting values in superglobals not allowed; please use setParam()'); }
/** * Set a new type, and convert the value * * @param $type new type to set * @throws Zend_Measure_Exception */ public function setType($type) { if (empty(self::$_UNITS[$type])) { throw Zend::exception('Zend_Measure_Exception', 'unknown type of number:' . $type); } $value = $this->toDecimal(parent::getValue(), parent::getType()); $value = $this->fromDecimal($value, $type); parent::setValue($value, $type, $this->_Locale); parent::setType($type); }
protected function __set($var, $value) { switch ($var) { case 'startMin': $var = 'start-min'; $value = $this->formatTimestamp($value); break; case 'startMax': $var = 'start-max'; $value = $this->formatTimestamp($value); break; case 'visibility': case 'projection': if (!Zend_Gdata_Data::isValid($value, $var)) { throw Zend::exception('Zend_Gdata_Exception', "Unsupported {$var} value: '{$value}'"); } $var = "_{$var}"; break; case 'orderby': if (!Zend_Gdata_Data::isValid($value, 'orderby#calendar')) { throw Zend::exception('Zend_Gdata_Exception', "Unsupported {$var} value: '{$value}'"); } break; case 'user': $var = '_user'; // @todo: validate user value break; case 'event': $var = '_event'; // @todo: validate event value break; case 'comments': $var = '_comments'; // @todo: validate comments subfeed value break; default: // other params are handled by parent break; } parent::__set($var, $value); }
/** * Find a matching route to the current PATH_INFO and inject * returning values to the Request object. * * @throws Zend_Controller_Router_Exception * @return Zend_Controller_Request_Abstract Request object */ public function route(Zend_Controller_Request_Abstract $request) { if (!$request instanceof Zend_Controller_Request_Http) { throw Zend::exception('Zend_Controller_Router_Exception', 'Zend_Controller_RewriteRouter requires a Zend_Controller_Request_Http-based request object'); } if ($this->useDefaultRoutes) { $this->addDefaultRoutes(); } $pathInfo = $request->getPathInfo(); /** Find the matching route */ foreach (array_reverse($this->_routes) as $name => $route) { if ($params = $route->match($pathInfo)) { foreach ($params as $param => $value) { $request->setParam($param, $value); } $this->_currentRoute = $name; break; } } return $request; }
/** * Get a specific cookie according to a URI and name * * @param Zend_Uri_Http|string $uri The uri (domain and path) to match * @param string $cookie_name The cookie's name * @param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings * @return Zend_Http_Cookie|string */ public function getCookie($uri, $cookie_name, $ret_as = self::COOKIE_OBJECT) { if (is_string($uri)) { $uri = Zend_Uri::factory($uri); } if (!$uri instanceof Zend_Uri_Http) { throw Zend::exception('Zend_Http_Exception', 'Invalid URI specified'); } // Get correct cookie path $path = $uri->getPath(); $path = substr($path, 0, strrpos($path, '/')); if (!$path) { $path = '/'; } if (isset($this->cookies[$uri->getHost()][$path][$cookie_name])) { $cookie = $this->cookies[$uri->getHost()][$path][$cookie_name]; switch ($ret_as) { case self::COOKIE_OBJECT: return $cookie; break; case self::COOKIE_STRING_ARRAY: case self::COOKIE_STRING_CONCAT: return $cookie->__toString(); break; default: throw Zend::exception('Zend_Http_Exception', "Invalid value passed for \$ret_as: {$ret_as}"); break; } } else { return false; } }
/** * Checks whether the cookie should be sent or not in a specific scenario * * @param string|Zend_Uri_Http $uri URI to check against (secure, domain, path) * @param boolean $matchSessionCookies Whether to send session cookies * @param int $now Override the current time when checking for expiry time * @return boolean */ public function match($uri, $matchSessionCookies = true, $now = null) { if (is_string($uri)) { $uri = Zend_Uri::factory($uri); } // Make sure we have a valid Zend_Uri_Http object if (!($uri->valid() && ($uri->getScheme() == 'http' || $uri->getScheme() == 'https'))) { throw Zend::exception('Zend_Http_Exception', 'Passed URI is not a valid HTTP or HTTPS URI'); } // Check that the cookie is secure (if required) and not expired if ($this->secure && $uri->getScheme() != 'https') { return false; } if ($this->isExpired($now)) { return false; } if ($this->isSessionCookie() && !$matchSessionCookies) { return false; } // Validate domain and path // Domain is validated using tail match, while path is validated using head match $domain_preg = preg_quote($this->getDomain(), "/"); if (!preg_match("/{$domain_preg}\$/", $uri->getHost())) { return false; } $path_preg = preg_quote($this->getPath(), "/"); if (!preg_match("/^{$path_preg}/", $uri->getPath())) { return false; } // If we didn't die until now, return true. return true; }
/** * Set response class/object * * Set the response object. The response is a container for action * responses and headers. Usage is optional. * * If a class name is provided, instantiates a response object. * * @param string|Zend_Controller_Response_Abstract $response * @throws Zend_Controller_Exception if invalid response class * @return Zend_Controller_Front */ public function setResponse($response) { if (is_string($response)) { Zend::loadClass($response); $response = new $response(); } if (!$response instanceof Zend_Controller_Response_Abstract) { throw Zend::exception('Zend_Controller_Exception', 'Invalid response class'); } $this->_response = $response; return $this; }
/** * Assembles user submitted parameters forming a URL path defined by this route * * @param array An array of variable and value pairs used as parameters * @return string Route path with user submitted parameters */ public function assemble($data = array(), $reset = false) { $url = array(); if (!$reset) { $data += $this->_params; } foreach ($this->_parts as $key => $part) { if (isset($part['name'])) { if (isset($data[$part['name']])) { $url[$key] = $data[$part['name']]; unset($data[$part['name']]); } elseif (isset($this->_values[$part['name']])) { $url[$key] = $this->_values[$part['name']]; } elseif (isset($this->_defaults[$part['name']])) { $url[$key] = $this->_defaults[$part['name']]; } else { throw Zend::exception('Zend_Controller_Router_Exception', $part['name'] . ' is not specified'); } } else { if ($part['regex'] != '\\*') { $url[$key] = $part['regex']; } else { foreach ($data as $var => $value) { $url[$var] = $var . self::URI_DELIMITER . $value; } } } } return implode(self::URI_DELIMITER, $url); }
/** * Getter for mail headers - name is matched in lowercase * * @param string $name header name * @throws Zend_Mail_Exception * @return string|array header line or array of headers if header exists more than once */ public function __get($name) { $name = strtolower($name); if (!isset($this->_headers[$name])) { throw Zend::exception('Zend_Mail_Exception', "no Header with Name {$name} found"); } return $this->_headers[$name]; }
/** * magic method for unserialize() * * with this method you can cache the mbox class * for cache validation the mtime of the mbox file is used */ public function __wakeup() { if ($this->_filemtime != filemtime($this->_filename)) { $this->close(); $this->_openMboxFile($this->_filename); } else { $this->_fh = @fopen($this->_filename, 'r'); if (!$this->_fh) { throw Zend::exception('Zend_Mail_Exception', 'cannot open mbox file'); } } }
/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; while ($line = fgets($this->socket)) { $response .= $line; if (!chop($line)) { break; } } // Handle 100 and 101 responses internally by restarting the read again if (Zend_Http_Response::extractCode($response) == 100 || Zend_Http_Response::extractCode($response) == 101) { return $this->read(); } // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); // if the connection is set to close, just read until socket closes if (isset($headers['connection']) && $headers['connection'] == 'close') { while ($buff = fread($this->socket, 8192)) { $response .= $buff; } $this->close(); // Else, if we got a transfer-encoding header (chunked body) } elseif (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $chunk = ''; $line = fgets($this->socket); $chunk .= $line; $hexchunksize = chop($line); $chunksize = hexdec(chop($line)); if (dechex($chunksize) != $hexchunksize) { fclose($this->socket); throw Zend::exception('Zend_Http_Client_Adapter_Exception', 'Invalid chunk size "' . $hexchunksize . '" unable to read chunked body'); } $left_to_read = $chunksize; while ($left_to_read > 0) { $chunk .= fread($this->socket, $left_to_read); $left_to_read = $chunksize - strlen($chunk); } $chunk .= fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw Zend::exception('Zend_Http_Client_Adapter_Exception', "Can't handle '" . $headers['transfer-encoding'] . "' transfer encoding"); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = fread($this->socket, $left_to_read); $left_to_read -= strlen($chunk); $response .= $chunk; } // Fallback: just read the response (should not happen) } else { while ($buff = fread($this->socket, 8192)) { $response .= $buff; } $this->close(); } return $response; }