public function getLatLng($address)
 {
     # address identifier
     $address_identifier = 'latlng_' . str_replace(array(' '), array('_'), $address);
     $address_identifier = preg_replace('/[^a-z0-9_]+/i', '', $address);
     # registry
     $registry = Zend_Registry::getInstance();
     # caching
     $frontendOptions = array('lifetime' => 2592000, 'automatic_serialization' => true);
     $backendOptions = array('cache_dir' => $registry->config->application->logs->tmpDir . '/cache/');
     $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
     # get data
     if (($data = $cache->load($address_identifier)) === false) {
         new Custom_Logging('Hit Google: Lat/Lng for ' . $address, Zend_Log::INFO);
         $client = new Zend_Http_Client('http://maps.google.com/maps/geo?q=' . urlencode($address), array('maxredirects' => 0, 'timeout' => 30));
         $request = $client->request();
         $response = Zend_Http_Response::fromString($request);
         $body = Zend_Json::decode($response->getBody());
         $data = array();
         $data['latitude'] = !empty($body['Placemark'][0]['Point']['coordinates'][1]) ? $body['Placemark'][0]['Point']['coordinates'][1] : null;
         $data['longitude'] = !empty($body['Placemark'][0]['Point']['coordinates'][0]) ? $body['Placemark'][0]['Point']['coordinates'][0] : null;
         $cache->save($data, $address_identifier);
     } else {
         new Custom_Logging('(local cache) Hit Google: Lat/Lng for ' . $address, Zend_Log::INFO);
     }
     return $data;
 }
 /**
  * Validate the response data from Correios.
  * This method will choose between Request Cache or Save in Cache
  * 
  * Step 1:
  *     Invalid responses must call the Cache load.
  *     Cache loading is requested by throwing adapter exception.
  *     
  * Step 2:
  *     To save valid responses, it must contain no errors.
  *     Errors are detected by pattern_nocache and returns false.
  *
  * @param string $data XML Content
  * 
  * @throws Zend_Http_Client_Adapter_Exception
  *
  * @return boolean
  */
 protected function _isValidCache($data)
 {
     // Step 1
     try {
         $response = Zend_Http_Response::fromString($data);
         $content = $response->getBody();
     } catch (Zend_Http_Exception $e) {
         throw new Zend_Http_Client_Adapter_Exception($e->getMessage());
     }
     if (empty($content)) {
         throw new Zend_Http_Client_Adapter_Exception();
     }
     libxml_use_internal_errors(true);
     $xml = simplexml_load_string($content);
     if (!$xml || !isset($xml->cServico)) {
         throw new Zend_Http_Client_Adapter_Exception();
     }
     // Step 2
     $pattern = $this->getConfigData('pattern_nocache');
     if ($pattern != '' && preg_match($pattern, $content, $matches)) {
         return false;
     }
     return true;
 }
Exemple #3
0
 /**
  * Retrieve entities from table
  * 
  * @param string $tableName|Zend_Service_WindowsAzure_Storage_TableEntityQuery    Table name -or- Zend_Service_WindowsAzure_Storage_TableEntityQuery instance
  * @param string $filter                                                Filter condition (not applied when $tableName is a Zend_Service_WindowsAzure_Storage_TableEntityQuery instance)
  * @param string $entityClass                                           Entity class name
  * @param string $nextPartitionKey                                      Next partition key, used for listing entities when total amount of entities is > 1000.
  * @param string $nextRowKey                                            Next row key, used for listing entities when total amount of entities is > 1000.
  * @return array Array of Zend_Service_WindowsAzure_Storage_TableEntity
  * @throws Zend_Service_WindowsAzure_Exception
  */
 public function retrieveEntities($tableName = '', $filter = '', $entityClass = 'Zend_Service_WindowsAzure_Storage_DynamicTableEntity', $nextPartitionKey = null, $nextRowKey = null)
 {
     if ($tableName === '') {
         require_once 'Zend/Service/WindowsAzure/Exception.php';
         throw new Zend_Service_WindowsAzure_Exception('Table name is not specified.');
     }
     if ($entityClass === '') {
         require_once 'Zend/Service/WindowsAzure/Exception.php';
         throw new Zend_Service_WindowsAzure_Exception('Entity class is not specified.');
     }
     // Convenience...
     if (class_exists($filter)) {
         $entityClass = $filter;
         $filter = '';
     }
     // Query string
     $queryString = '';
     // Determine query
     if (is_string($tableName)) {
         // Option 1: $tableName is a string
         // Append parentheses
         if (strpos($tableName, '()') === false) {
             $tableName .= '()';
         }
         // Build query
         $query = array();
         // Filter?
         if ($filter !== '') {
             $query[] = '$filter=' . Zend_Service_WindowsAzure_Storage_TableEntityQuery::encodeQuery($filter);
         }
         // Build queryString
         if (count($query) > 0) {
             $queryString = '?' . implode('&', $query);
         }
     } else {
         if (get_class($tableName) == 'Zend_Service_WindowsAzure_Storage_TableEntityQuery') {
             // Option 2: $tableName is a Zend_Service_WindowsAzure_Storage_TableEntityQuery instance
             // Build queryString
             $queryString = $tableName->assembleQueryString(true);
             // Change $tableName
             $tableName = $tableName->assembleFrom(true);
         } else {
             require_once 'Zend/Service/WindowsAzure/Exception.php';
             throw new Zend_Service_WindowsAzure_Exception('Invalid argument: $tableName');
         }
     }
     // Add continuation querystring parameters?
     if (!is_null($nextPartitionKey) && !is_null($nextRowKey)) {
         if ($queryString !== '') {
             $queryString .= '&';
         } else {
             $queryString .= '?';
         }
         $queryString .= 'NextPartitionKey=' . rawurlencode($nextPartitionKey) . '&NextRowKey=' . rawurlencode($nextRowKey);
     }
     // Perform request
     $response = null;
     if ($this->isInBatch() && $this->getCurrentBatch()->getOperationCount() == 0) {
         $this->getCurrentBatch()->enlistOperation($tableName, $queryString, Zend_Http_Client::GET, array(), true, null);
         $response = $this->getCurrentBatch()->commit();
         // Get inner response (multipart)
         $innerResponse = $response->getBody();
         $innerResponse = substr($innerResponse, strpos($innerResponse, 'HTTP/1.1 200 OK'));
         $innerResponse = substr($innerResponse, 0, strpos($innerResponse, '--batchresponse'));
         $response = Zend_Http_Response::fromString($innerResponse);
     } else {
         $response = $this->_performRequest($tableName, $queryString, Zend_Http_Client::GET, array(), true, null);
     }
     if ($response->isSuccessful()) {
         // Parse result
         $result = $this->_parseResponse($response);
         if (!$result) {
             return array();
         }
         $entries = null;
         if ($result->entry) {
             if (count($result->entry) > 1) {
                 $entries = $result->entry;
             } else {
                 $entries = array($result->entry);
             }
         } else {
             // This one is tricky... If we have properties defined, we have an entity.
             $properties = $result->xpath('//m:properties');
             if ($properties) {
                 $entries = array($result);
             } else {
                 return array();
             }
         }
         // Create return value
         $returnValue = array();
         foreach ($entries as $entry) {
             // Parse properties
             $properties = $entry->xpath('.//m:properties');
             $properties = $properties[0]->children('http://schemas.microsoft.com/ado/2007/08/dataservices');
             // Create entity
             $entity = new $entityClass('', '');
             $entity->setAzureValues((array) $properties, $this->_throwExceptionOnMissingData);
             // If we have a Zend_Service_WindowsAzure_Storage_DynamicTableEntity, make sure all property types are set
             if ($entity instanceof Zend_Service_WindowsAzure_Storage_DynamicTableEntity) {
                 foreach ($properties as $key => $value) {
                     $attributes = $value->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
                     $type = (string) $attributes['type'];
                     if ($type !== '') {
                         $entity->setAzureProperty($key, (string) $value, $type);
                     }
                 }
             }
             // Update etag
             $etag = $entry->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
             $etag = (string) $etag['etag'];
             $entity->setEtag($etag);
             // Add to result
             $returnValue[] = $entity;
         }
         // More entities?
         if (!is_null($response->getHeader('x-ms-continuation-NextPartitionKey')) && !is_null($response->getHeader('x-ms-continuation-NextRowKey'))) {
             if (strpos($queryString, '$top') === false) {
                 $returnValue = array_merge($returnValue, $this->retrieveEntities($tableName, $filter, $entityClass, $response->getHeader('x-ms-continuation-NextPartitionKey'), $response->getHeader('x-ms-continuation-NextRowKey')));
             }
         }
         // Return
         return $returnValue;
     } else {
         require_once 'Zend/Service/WindowsAzure/Exception.php';
         throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
     }
 }
 /**
  * Test that parsing a multibyte-encoded chunked response works.
  *
  * This can potentially fail on different PHP environments - for example
  * when mbstring.func_overload is set to overload strlen().
  *
  */
 public function testMultibyteChunkedResponse()
 {
     $md5 = 'ab952f1617d0e28724932401f2d3c6ae';
     $response = Zend_Http_Response::fromString($this->readResponse('response_multibyte_body'));
     $this->assertEquals($md5, md5($response->getBody()));
 }
 /**
  * Uses the adapter to request the given url and returns
  * its response.
  *
  * Example:
  *
  *     $this->request('http://www.example.com/test.html');
  *
  * @param string $url
  * @return Zend_Http_Response
  */
 protected function request($url)
 {
     $this->adapter->connect('');
     $this->adapter->write('GET', Zend_Uri_Http::fromString($url));
     $response = $this->adapter->read();
     $this->adapter->close();
     return Zend_Http_Response::fromString($response);
 }
 public function testMultilineHeader()
 {
     $response = Zend_Http_Response::fromString($this->readResponse('response_multiline_header'));
     // Make sure we got the corrent no. of headers
     $this->assertEquals(6, count($response->getHeaders()), 'Header count is expected to be 6');
     // Check header integrity
     $this->assertEquals('timeout=15, max=100', $response->getHeader('keep-alive'));
     $this->assertEquals('text/html; charset=iso-8859-1', $response->getHeader('content-type'));
 }
 /**
  * Test we can build a new object from a response object (multiple cookie headers)
  */
 public function testFromResponseMultiHeader()
 {
     $res_str = file_get_contents(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'response_with_cookies');
     $response = Zend_Http_Response::fromString($res_str);
     $jar = Zend_Http_CookieJar::fromResponse($response, 'http://www.example.com');
     $this->assertTrue($jar instanceof Zend_Http_CookieJar, '$jar is not an instance of CookieJar as expected');
     $this->assertEquals(3, count($jar->getAllCookies()), 'CookieJar expected to contain 3 cookies');
 }
 public function makeHttpResponseFor($nativeVars)
 {
     $response = $this->getServerResponseFor($nativeVars);
     return Zend_Http_Response::fromString($response);
 }
Exemple #9
0
 /**
  * Do some checks before install.
  *
  * @throws Expeption If the server don't have the requirements.
  *
  * @return void
  */
 private function _checkServer()
 {
     $missingRequirements = array();
     // The following extensions are either needed by components of the Zend Framework that are used
     // or by P6 components itself.
     $extensionsNeeded = array('mbstring', 'iconv', 'ctype', 'gd', 'pcre', 'pdo', 'Reflection', 'session', 'SPL', 'zlib');
     // These settings need to be properly configured by the admin
     $settingsNeeded = array('magic_quotes_gpc' => 0, 'magic_quotes_runtime' => 0, 'magic_quotes_sybase' => 0);
     // These settings should be properly configured by the admin
     $settingsRecommended = array('register_globals' => 0, 'safe_mode' => 0);
     // Check the PHP version
     $requiredPhpVersion = "5.2.4";
     if (version_compare(phpversion(), $requiredPhpVersion, '<')) {
         // This is a requirement of the Zend Framework
         $missingRequirements[] = "PHP Version {$requiredPhpVersion} or newer";
     }
     foreach ($extensionsNeeded as $extension) {
         if (!extension_loaded($extension)) {
             $missingRequirements[] = "The {$extension} extension must be enabled.";
         }
     }
     // Check pdo library
     $mysql = extension_loaded('pdo_mysql');
     $sqlite = extension_loaded('pdo_sqlite2');
     $pgsql = extension_loaded('pdo_pgsql');
     if (!$mysql && !$sqlite && !$pgsql) {
         $missingRequirements[] = "You need one of these PDO extensions: pdo_mysql, pdo_pgsql or pdo_sqlite";
     }
     foreach ($settingsNeeded as $conf => $value) {
         if (ini_get($conf) != $value) {
             $missingRequirements[] = "The php.ini setting of \"{$conf}\" has to be \"{$value}\".";
         }
     }
     // Checking if configuration.php exists
     $baseDir = str_replace('htdocs/setup.php', '', $_SERVER['SCRIPT_FILENAME']);
     if (file_exists($baseDir . "configuration.php")) {
         throw new Exception("Configuration file found. Please, delete it before run setup again.");
     }
     if (!empty($missingRequirements)) {
         $message = implode("\n", $missingRequirements);
         throw new Exception($message);
     }
     if (strncmp($_SERVER['SCRIPT_NAME'], '/setup.php', 10) != 0) {
         $this->_message[] = "It is recommend install PHProjekt 6 using a virtual host.<br />" . "You should try to generate an extra virtual host (or a sub-domain) to phprojekt/htdocs.";
         // Works the .htaccess?
         $response = new Zend_Controller_Request_Http();
         $webpath = $response->getHttpHost();
         $str = '';
         $sock = fsockopen($webpath, $response->getServer('SERVER_PORT'));
         $request = "GET " . str_replace('htdocs/setup.php', '', $response->getRequestUri()) . '/application/' . " HTTP/1.1\r\n" . "Host: " . $webpath . "\r\nConnection: close\r\n\r\n";
         fwrite($sock, $request);
         while ($buff = fread($sock, 1024)) {
             $str .= $buff;
         }
         $response = Zend_Http_Response::fromString($str);
         if ($response->getStatus() != '403') {
             $this->_message[] = "Please note that your webserver needs to support .htaccess files " . "to deny access to the configuration files.<br />" . "Running PHProjekt 6 without using the provided .htaccess files to deny access to " . "certain files and folders, might not be secure and is not recommended.";
         }
         fclose($sock);
     }
     foreach ($settingsRecommended as $conf => $value) {
         if (ini_get($conf) != $value) {
             $this->_message[] = "It is recommend to have \"{$conf}\" set to \"{$value}\", but it is not required " . "to run PHProjekt.";
         }
     }
 }
Exemple #10
0
 /**
  * Do some checks before install.
  *
  * @throws Expeption If the server don't have the requirements.
  *
  * @return void
  */
 private function _checkServer()
 {
     // Check the server
     $checkServer = Phprojekt::checkExtensionsAndSettings();
     // Check the PHP version
     if (!$checkServer['requirements']['php']['checked']) {
         $missingRequirements[] = "You need the PHP Version " . $checkServer['requirements']['php']['required'] . " or newer. Follow this link for help: <a href=\"" . $checkServer['requirements']['php']['help'] . "\"" . " target=\"_new\">HELP</a>";
     }
     // Check required extension
     foreach ($checkServer['requirements']['extension'] as $name => $values) {
         if (!$values['checked']) {
             $missingRequirements[] = "The '" . $name . "' extension must be enabled. Follow this link for help: " . "<a href=\"" . $values['help'] . "\" target=\"_new\">HELP</a>";
         }
     }
     // Check required settings
     foreach ($checkServer['requirements']['settings'] as $name => $values) {
         if (!$values['checked']) {
             $missingRequirements[] = "The php.ini setting of '" . $name . "' has to be '" . $values['required'] . "'. Follow this link for help: <a href=\"" . $values['help'] . "\"" . " target=\"_new\">HELP</a>";
         }
     }
     // Checking if configuration.php exists
     $baseDir = str_replace('htdocs/setup.php', '', $_SERVER['SCRIPT_FILENAME']);
     if (file_exists($baseDir . "configuration.php")) {
         throw new Exception("Configuration file found. Please, delete it before run setup again.");
     }
     if (!empty($missingRequirements)) {
         $message = implode("\n", $missingRequirements);
         throw new Exception($message);
     }
     if (strncmp($_SERVER['SCRIPT_NAME'], '/setup.php', 10) != 0) {
         $this->_message[] = "It is recommend install PHProjekt 6 using a virtual host.<br />" . "You should try to generate an extra virtual host (or a sub-domain) to phprojekt/htdocs.";
         // Works the .htaccess?
         $response = new Zend_Controller_Request_Http();
         $webpath = $response->getHttpHost();
         $str = '';
         $sock = fsockopen($webpath, $response->getServer('SERVER_PORT'));
         $request = "GET " . str_replace('htdocs/setup.php', '', $response->getRequestUri()) . '/application/' . " HTTP/1.1\r\n" . "Host: " . $webpath . "\r\nConnection: close\r\n\r\n";
         fwrite($sock, $request);
         while ($buff = fread($sock, 1024)) {
             $str .= $buff;
         }
         $response = Zend_Http_Response::fromString($str);
         if ($response->getStatus() != '403') {
             $this->_message[] = "Please note that your webserver needs to support .htaccess files " . "to deny access to the configuration files.<br />" . "Running PHProjekt 6 without using the provided .htaccess files to deny access to " . "certain files and folders, might not be secure and is not recommended.";
         }
         fclose($sock);
     }
     foreach ($checkServer['recommendations']['settings'] as $name => $values) {
         if (!$values['checked']) {
             $this->_message[] = "It is recommend to have '" . $name . "' set to '" . $values['required'] . "', but it is not required to run PHProjekt. Follow this link for help: <a href=\"" . $values['help'] . "\" target=\"_new\">HELP</a>";
         }
     }
 }
 /**
  * Test that responses could be added as objects (ZF-7009)
  *
  * @link http://framework.zend.com/issues/browse/ZF-7009
  * @dataProvider validHttpResponseProvider
  */
 public function testAddResponseAsObject($testResponse)
 {
     $this->adapter->read();
     // pop out first response
     $respObj = Zend_Http_Response::fromString($testResponse);
     $this->adapter->addResponse($respObj);
     $this->assertEquals($testResponse, $this->adapter->read());
 }
 /**
  * Second half of Zend_Http_Client's request method
  * removed the end of the do-while loop and the
  * redirect code.
  *
  * @return Zend_Http_Response
  **/
 public function getResponse()
 {
     $response = $this->adapter->read();
     if (!$response) {
         require_once 'Zend/Http/Client/Exception.php';
         throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
     }
     $response = Zend_Http_Response::fromString($response);
     if ($this->config['storeresponse']) {
         $this->last_response = $response;
     }
     // Load cookies into cookie jar
     if (isset($this->cookiejar)) {
         $this->cookiejar->addCookiesFromResponse($response, $uri);
     }
     return $response;
 }
Exemple #13
0
 /**
  * Validate the response data from Correios.
  *
  * @param string $data XML Content
  *
  * @return boolean
  */
 protected function _isValidCache($data)
 {
     $response = Zend_Http_Response::fromString($data);
     $content = $response->getBody();
     $pattern = $this->getConfigData('pattern_nocache');
     if ($pattern != '' && preg_match($pattern, $content, $matches)) {
         return false;
     }
     if (empty($content)) {
         return false;
     }
     libxml_use_internal_errors(true);
     $xml = simplexml_load_string($content);
     if (!$xml || !isset($xml->cServico)) {
         return false;
     }
     return true;
 }
 /**
  * Test that parsing a multibyte-encoded chunked response works.
  *
  * This can potentially fail on different PHP environments - for example
  * when mbstring.func_overload is set to overload strlen().
  *
  */
 public function testMultibyteChunkedResponse()
 {
     $md5 = 'f734924685f92b243c8580848cadc560';
     $response = Zend_Http_Response::fromString($this->readResponse('response_multibyte_body'));
     $this->assertEquals($md5, md5($response->getBody()));
 }
 /**
  * Retrieve the Document key reference id number from the remote
  * document production server
  *
  * @param int $customerid Customer Id number
  * @param $documentid
  * @param string $keyrefname Key reference name
  * @throws Application_Soap_Fault
  * @internal param \documentid $int Document Id number
  * @return int
  */
 private function getDocKeyReferenceId($customerid, $documentid, $keyrefname)
 {
     $keyrefid = null;
     // Discover customer id from customer name
     $this->httpclient->setParameterGet(array('PHPSESSID' => $this->sessionid, 'action' => 'GetKeyRefsList', 'CustomerID' => $customerid, 'DocTypeID' => $documentid));
     try {
         $response = $this->httpclient->request('GET');
     } catch (Zend_Http_Client_Exception $ex) {
         error_log(__FILE__ . ':' . __LINE__ . ':' . $ex->getMessage());
         throw new Application_Soap_Fault('Failure calling DMS server', 'Server');
     }
     $this->_debugRequest($this->httpclient);
     if (is_string($response)) {
         $response = Zend_Http_Response::fromString($response);
     } else {
         if (!$response instanceof Zend_Http_Response) {
             // Some other response returned, don't know how to process.
             // The request is queued, so return a fault.
             error_log(__FILE__ . ':' . __LINE__ . ':DMS server returned unknown response');
             throw new Application_Soap_Fault('DMS server returned unknown response', 'Server');
         }
     }
     try {
         $response = $response->getBody();
         $keyreflistresponse = Zend_Json::decode($response);
     } catch (Exception $ex) {
         // Problem requesting service, report the problem back but keep the queue record
         error_log(__FILE__ . ':' . __LINE__ . ':' . $ex->getMessage());
         throw new Application_Soap_Fault('DMS server returned invalid response', 'Server');
     }
     $this->httpclient->resetParameters();
     array_shift($keyreflistresponse);
     // Remove the first element, this is a header
     foreach ($keyreflistresponse as $keyreference) {
         // Seach for the customer id that matches the customer code
         if ($keyreference[2] == $keyrefname) {
             $keyrefid = $keyreference[0];
             break;
         }
     }
     if ($keyrefid == null) {
         // customer id not found
         error_log(__FILE__ . ':' . __LINE__ . ':Document Key reference Id not found on DMS server');
         throw new Application_Soap_Fault('Document Key reference Id not found on DMS server', 'Server');
     }
     return $keyrefid;
 }
Exemple #16
0
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $method
  * @return Zend_Http_Response
  * @throws Zend_Http_Client_Exception
  */
 public function request($method = null)
 {
     if (!$this->uri instanceof Zend_Uri_Http) {
         /** @see Zend_Http_Client_Exception */
         require_once 'Zend/Http/Client/Exception.php';
         throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
     }
     if ($method) {
         $this->setMethod($method);
     }
     $this->redirectCounter = 0;
     $response = null;
     // Make sure the adapter is loaded
     if ($this->adapter == null) {
         $this->setAdapter($this->config['adapter']);
     }
     // Send the first request. If redirected, continue.
     do {
         // Clone the URI and add the additional GET parameters to it
         $uri = clone $this->uri;
         if (!empty($this->paramsGet)) {
             $query = $uri->getQuery();
             if (!empty($query)) {
                 $query .= '&';
             }
             $query .= http_build_query($this->paramsGet, null, '&');
             $uri->setQuery($query);
         }
         $body = $this->_prepareBody();
         $headers = $this->_prepareHeaders();
         // Open the connection, send the request and read the response
         $this->adapter->connect($uri->getHost(), $uri->getPort(), $uri->getScheme() == 'https' ? true : false);
         $this->last_request = $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body);
         $response = $this->adapter->read();
         if (!$response) {
             /** @see Zend_Http_Client_Exception */
             require_once 'Zend/Http/Client/Exception.php';
             throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
         }
         $response = Zend_Http_Response::fromString($response);
         if ($this->config['storeresponse']) {
             $this->last_response = $response;
         }
         // Load cookies into cookie jar
         if (isset($this->cookiejar)) {
             $this->cookiejar->addCookiesFromResponse($response, $uri);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatus() == 303 || !$this->config['strictredirects'] && ($response->getStatus() == 302 || $response->getStatus() == 301)) {
                 $this->resetParameters();
                 $this->setMethod(self::GET);
             }
             // If we got a well formed absolute URI
             if (Zend_Uri_Http::check($location)) {
                 $this->setHeaders('host', null);
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 if (strpos($location, '?') !== false) {
                     list($location, $query) = explode('?', $location, 2);
                 } else {
                     $query = '';
                 }
                 $this->uri->setQuery($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->uri->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = $this->uri->getPath();
                     $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
                     $this->uri->setPath($path . '/' . $location);
                 }
             }
             ++$this->redirectCounter;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter < $this->config['maxredirects']);
     return $response;
 }
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $method
  * @return Zend_Http_Response
  * @throws Zend_Http_Client_Exception
  */
 public function request($method = null)
 {
     if (!$this->uri instanceof Zend_Uri_Http) {
         /** @see Zend_Http_Client_Exception */
         require_once 'Zend/Http/Client/Exception.php';
         throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
     }
     if ($method) {
         $this->setMethod($method);
     }
     $this->redirectCounter = 0;
     $response = null;
     // Make sure the adapter is loaded
     if ($this->adapter == null) {
         $this->setAdapter($this->config['adapter']);
     }
     // Send the first request. If redirected, continue.
     do {
         // Clone the URI and add the additional GET parameters to it
         $uri = clone $this->uri;
         if (!empty($this->paramsGet)) {
             $query = $uri->getQuery();
             if (!empty($query)) {
                 $query .= '&';
             }
             $query .= http_build_query($this->paramsGet, null, '&');
             if ($this->config['rfc3986_strict']) {
                 $query = str_replace('+', '%20', $query);
             }
             // @see ZF-11671 to unmask for some services to foo=val1&foo=val2
             if ($this->getUnmaskStatus()) {
                 if ($this->_queryBracketsEscaped) {
                     $query = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query);
                 } else {
                     $query = preg_replace('/\\[(?:[0-9]|[1-9][0-9]+)\\]=/', '=', $query);
                 }
             }
             $uri->setQuery($query);
         }
         $body = $this->_prepareBody();
         $headers = $this->_prepareHeaders();
         // check that adapter supports streaming before using it
         if (is_resource($body) && !$this->adapter instanceof Zend_Http_Client_Adapter_Stream) {
             /** @see Zend_Http_Client_Exception */
             require_once 'Zend/Http/Client/Exception.php';
             throw new Zend_Http_Client_Exception('Adapter does not support streaming');
         }
         // Open the connection, send the request and read the response
         $this->adapter->connect($uri->getHost(), $uri->getPort(), $uri->getScheme() == 'https' ? true : false);
         if ($this->config['output_stream']) {
             if ($this->adapter instanceof Zend_Http_Client_Adapter_Stream) {
                 $stream = $this->_openTempStream();
                 $this->adapter->setOutputStream($stream);
             } else {
                 /** @see Zend_Http_Client_Exception */
                 require_once 'Zend/Http/Client/Exception.php';
                 throw new Zend_Http_Client_Exception('Adapter does not support streaming');
             }
         }
         $this->last_request = $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body);
         $response = $this->adapter->read();
         if (!$response) {
             /** @see Zend_Http_Client_Exception */
             require_once 'Zend/Http/Client/Exception.php';
             throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
         }
         if ($this->config['output_stream']) {
             $streamMetaData = stream_get_meta_data($stream);
             if ($streamMetaData['seekable']) {
                 rewind($stream);
             }
             // cleanup the adapter
             $this->adapter->setOutputStream(null);
             $response = Zend_Http_Response_Stream::fromStream($response, $stream);
             $response->setStreamName($this->_stream_name);
             if (!is_string($this->config['output_stream'])) {
                 // we used temp name, will need to clean up
                 $response->setCleanup(true);
             }
         } else {
             $response = Zend_Http_Response::fromString($response);
         }
         if ($this->config['storeresponse']) {
             $this->last_response = $response;
         }
         // Load cookies into cookie jar
         if (isset($this->cookiejar)) {
             $this->cookiejar->addCookiesFromResponse($response, $uri, $this->config['encodecookies']);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
             // Avoid problems with buggy servers that add whitespace at the
             // end of some headers (See ZF-11283)
             $location = trim($location);
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatus() == 303 || !$this->config['strictredirects'] && ($response->getStatus() == 302 || $response->getStatus() == 301)) {
                 $this->resetParameters();
                 $this->setMethod(self::GET);
             }
             // If we got a well formed absolute URI
             if (($scheme = substr($location, 0, 6)) && ($scheme == 'http:/' || $scheme == 'https:')) {
                 $this->setHeaders('host', null);
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 if (strpos($location, '?') !== false) {
                     list($location, $query) = explode('?', $location, 2);
                 } else {
                     $query = '';
                 }
                 $this->uri->setQuery($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->uri->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = $this->uri->getPath();
                     $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
                     $this->uri->setPath($path . '/' . $location);
                 }
             }
             ++$this->redirectCounter;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter < $this->config['maxredirects']);
     return $response;
 }
 /**
  * Authenticate with the remote document production server
  * Sets the property httpclient to an instance of Zend_Http_Client
  * for further interaction with the document production server.
  *
  * @return bool
  */
 private function _remoteServerAuthentication()
 {
     $config = Zend_Registry::get('params');
     $host = '';
     $authk = '';
     $requesttimeout = '';
     // Capture DMS service parameters
     if (isset($config->dms) && isset($config->dms->requestHost)) {
         $host = $config->dms->requestHost;
     }
     if (isset($config->dms) && isset($config->dms->authToken)) {
         $authk = $config->dms->authToken;
     }
     if (isset($config->dms) && isset($config->dms->requestTimeout)) {
         $requesttimeout = $config->dms->requestTimeout;
     }
     if (isset($config->dms) && isset($config->dms->customercode)) {
         $customercode = $config->dms->customercode;
     }
     // Validate parameters are ok
     if (!isset($host) || $host == '') {
         error_log(__FILE__ . ':' . __LINE__ . ':DMS service host not set');
         throw new Exception('DMS service host not set');
     }
     if (!isset($authk) || $authk == '') {
         error_log(__FILE__ . ':' . __LINE__ . ':DMS service auth token not set');
         throw new Exception('DMS service auth token not set');
     }
     if (!isset($requesttimeout) || $requesttimeout == '') {
         // Default to 15 seconds
         $requesttimeout = 15;
     }
     $client = new Zend_Http_Client($host . '?action=UserAuth&language=gb&cc=' . $customercode, array('maxredirects' => 0, 'timeout' => $requesttimeout, 'keepalive' => true));
     // Set the adapter
     $client->setAdapter(new Zend_Http_Client_Adapter_Curl());
     // Disable SSL certificate verification, fails in testing
     $client->getAdapter()->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
     $client->getAdapter()->setCurlOption(CURLOPT_SSL_VERIFYPEER, false);
     // Login to DMS service
     $client->setParameterPost(array('authmethod' => '1', 'AuthK' => $authk, 'login' => '', 'password' => ''));
     try {
         $response = $client->request('POST');
     } catch (Zend_Http_Client_Exception $ex) {
         error_log(__FILE__ . ':' . __LINE__ . ':' . $ex->getMessage());
         throw new Exception('Failure calling DMS server');
     }
     $this->_debugRequest($client);
     if (is_string($response)) {
         $response = Zend_Http_Response::fromString($response);
     } else {
         if (!$response instanceof Zend_Http_Response) {
             // Some other response returned, don't know how to process.
             // The request is queued, so return a fault.
             error_log(__FILE__ . ':' . __LINE__ . ':' . $ex->getMessage());
             throw new Exception('DMS server returned unknown response');
         }
     }
     try {
         $response = $response->getBody();
         $loginresponse = Zend_Json::decode($response);
     } catch (Exception $ex) {
         // Problem requesting service, report the problem back but keep the queue record
         error_log(__FILE__ . ':' . __LINE__ . ':' . $ex->getMessage());
         throw new Exception('DMS server returned invalid response');
     }
     $client->resetParameters();
     // Check login response
     if ($loginresponse == null) {
         // Problem authenticating with DMS server
         error_log(__FILE__ . ':' . __LINE__ . ':Failed to auth DMS server for request');
         throw new Exception('Failed to auth DMS server for request');
     }
     // Make request for creation
     $client->setUri($host);
     // Remove get parameters from original login uri
     $this->httpclient = $client;
     $this->sessionid = $loginresponse['SessionId'];
     $this->customercode = $customercode;
     return true;
 }