getLastRequest() public method

Get the last HTTP request as string
public getLastRequest ( ) : string
return string
 public function validate($username, $password)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Options: ' . print_r($this->_options, true));
     }
     $url = isset($this->_options['url']) ? $this->_options['url'] : 'https://localhost/validate/check';
     $adapter = new Zend_Http_Client_Adapter_Socket();
     $adapter->setStreamContext($this->_options = array('ssl' => array('verify_peer' => isset($this->_options['ignorePeerName']) ? false : true, 'allow_self_signed' => isset($this->_options['allowSelfSigned']) ? true : false)));
     $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30));
     $client->setAdapter($adapter);
     $params = array('user' => $username, 'pass' => $password);
     $client->setParameterPost($params);
     try {
         $response = $client->request(Zend_Http_Client::POST);
     } catch (Zend_Http_Client_Adapter_Exception $zhcae) {
         Tinebase_Exception::log($zhcae);
         return Tinebase_Auth::FAILURE;
     }
     $body = $response->getBody();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Request: ' . $client->getLastRequest());
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Response: ' . $body);
     }
     if ($response->getStatus() !== 200) {
         return Tinebase_Auth::FAILURE;
     }
     $result = Tinebase_Helper::jsonDecode($body);
     if (isset($result['result']) && $result['result']['status'] === true && $result['result']['value'] === true) {
         return Tinebase_Auth::SUCCESS;
     } else {
         return Tinebase_Auth::FAILURE;
     }
 }
コード例 #2
0
ファイル: SocketTest.php プロジェクト: lortnus/zf1
 /**
  * Test that setting the same parameter twice in the query string does not
  * get reduced to a single value only.
  *
  */
 public function testDoubleGetParameter()
 {
     $qstr = 'foo=bar&foo=baz';
     $this->client->setUri($this->baseuri . 'testGetData.php?' . $qstr);
     $res = $this->client->request('GET');
     $this->assertContains($qstr, $this->client->getLastRequest(), 'Request is expected to contain the entire query string');
 }
コード例 #3
0
ファイル: Translate.php プロジェクト: sb15/zend-ex-legacy
 public function translate($message, $from, $to)
 {
     $url = "http://ajax.googleapis.com/ajax/services/language/translate";
     $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30));
     $langpair = $from . '|' . $to;
     $params = array('v' => '1.1', 'q' => $message, 'langpair' => $langpair, 'key' => 'ABQIAAAAMtXAc56OizxVFR_fG__ZZRSrxD5q6_ZpfA55q8xveFjTjZJnShSvPHZq2PGkhSBZ0_OObHUNyy0smw');
     /**
      * Zend_Http_Client
      */
     $client->setParameterPost($params);
     $client->setHeaders('Referer', 'http://sb6.ru');
     $response = $client->request("POST");
     //print_r ($response);
     $data = $response->getBody();
     $serverResult = json_decode($data);
     $status = $serverResult->responseStatus;
     // should be 200
     $result = '';
     if ($status == 200) {
         $result = $serverResult->responseData->translatedText;
     } else {
         echo "retry\n";
         print_r($client->getLastRequest());
         print_r($client->getLastResponse());
         die;
         return $this->translate($message, $from, $to);
     }
     return $result;
 }
コード例 #4
0
 /**
  * Test we can get the last request as string
  *
  */
 public function testGetLastRequest()
 {
     $this->client->setUri($this->baseuri . 'testHeaders.php');
     $this->client->setParameterGet('someinput', 'somevalue');
     $this->client->setHeaders(array('X-Powered-By' => 'My Glorious Golden Ass'));
     $res = $this->client->request(Zend_Http_Client::TRACE);
     $this->assertEquals($this->client->getLastRequest(), $res->getBody(), 'Response body should be exactly like the last request');
 }
コード例 #5
0
ファイル: CommonHttpTests.php プロジェクト: bradley-holt/zf2
 /**
  * Test we can get the last request as string
  *
  */
 public function testGetLastRequest()
 {
     $this->client->setUri($this->baseuri . 'testHeaders.php');
     $this->client->setParameterGet('someinput', 'somevalue');
     $this->client->setHeaders(array('X-Powered-By' => 'My Glorious Golden Ass'));
     $res = $this->client->request(HTTPClient::TRACE);
     if ($res->getStatus() == 405 || $res->getStatus() == 501) {
         $this->markTestSkipped("Server does not allow the TRACE method");
     }
     $this->assertEquals($this->client->getLastRequest(), $res->getBody(), 'Response body should be exactly like the last request');
 }
コード例 #6
0
 /**
  * @group ZF-10645
  */
 public function testPutRequestsHonorSpecifiedContentType()
 {
     $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
     $this->client->setMethod(Zend_Http_Client::PUT);
     $data = array('foo' => 'bar');
     $this->client->setRawData(http_build_query($data), 'text/html; charset=ISO-8859-1');
     $response = $this->client->request();
     $request = $this->client->getLastRequest();
     $this->assertContains('text/html; charset=ISO-8859-1', $request, $request);
     $this->assertContains('REQUEST_METHOD: PUT', $response->getBody(), $response->getBody());
 }
コード例 #7
0
ファイル: StaticTest.php プロジェクト: jsnshrmn/Suma
 /**
  * Test that we properly calculate the content-length of multibyte-encoded
  * request body
  *
  * This may file in case that mbstring overloads the substr and strlen
  * functions, and the mbstring internal encoding is a multibyte encoding.
  *
  * @link http://framework.zend.com/issues/browse/ZF-2098
  */
 public function testMultibyteRawPostDataZF2098()
 {
     $this->_client->setAdapter('Zend_Http_Client_Adapter_Test');
     $this->_client->setUri('http://example.com');
     $bodyFile = dirname(__FILE__) . '/_files/ZF2098-multibytepostdata.txt';
     $this->_client->setRawData(file_get_contents($bodyFile), 'text/plain');
     $this->_client->request('POST');
     $request = $this->_client->getLastRequest();
     if (!preg_match('/^content-length:\\s+(\\d+)/mi', $request, $match)) {
         $this->fail("Unable to find content-length header in request");
     }
     $this->assertEquals(filesize($bodyFile), (int) $match[1]);
 }
コード例 #8
0
 /**
  * @group ZF-11418
  */
 public function testMultiplePuts()
 {
     $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
     $data = 'test';
     $this->client->setRawData($data, 'text/plain');
     $this->client->setMethod(Zend_Http_Client::PUT);
     $response = $this->client->request();
     $this->assertContains('REQUEST_METHOD: PUT', $response->getBody(), $response->getBody());
     $this->client->resetParameters(true);
     $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
     $this->client->setMethod(Zend_Http_Client::PUT);
     $response = $this->client->request();
     $request = $this->client->getLastRequest();
     $this->assertNotContains('Content-Type: text/plain', $request);
 }
コード例 #9
0
 /**
  * @throws OpenSocial_Rest_Exception
  * @param  $serviceType
  * @param Zend_Http_Response $response
  * @return array
  */
 protected function _mapResponseToModels($serviceType, Zend_Http_Response $response)
 {
     if (strpos($response->getHeader('Content-Type'), 'application/json') !== 0) {
         throw new OpenSocial_Rest_Exception("Unknown Content-Type for response:<br /> " . var_export($response, true) . ' with body: ' . var_export($response->getBody(), true) . ' for request: ' . $this->_httpClient->getLastRequest());
     }
     $modelClass = 'OpenSocial_Model_' . $this->_getModelTypeForService($serviceType);
     if (!class_exists($modelClass, true)) {
         throw new OpenSocial_Rest_Exception("Model class {$modelClass} not found for service {$serviceType}!");
     }
     /**
      * @var OpenSocial_Rest_Mapper_Interface $mapper
      */
     $mapper = new OpenSocial_Rest_Mapper_Json($modelClass);
     return $mapper->map($response->getBody());
 }
コード例 #10
0
ファイル: HttpBox.php プロジェクト: bsa-git/zf-myblog
 /**
  * Get Stream Data.
  *
  *
  * $data can also be stream (such as file) to which the data will be save.
  * 
  * $client->setStream(); // will use temp file
  * $response = $client->request('GET');
  * // copy file
  * copy($response->getStreamName(), "my/downloads/file");
  * // use stream
  * $fp = fopen("my/downloads/file2", "w");
  * stream_copy_to_stream($response->getStream(), $fp);
  * // Also can write to known file
  * $client->setStream("my/downloads/myfile")->request('GET');
  * 
  * @param resource $data
  * @param string $enctype
  * @return Default_Plugin_HttpBox
  */
 function getStreamData($filename = null)
 {
     if (is_string($filename)) {
         $this->client->setStream($filename)->request('GET');
     } else {
         $this->client->setStream();
         // will use temp file
         $this->client->request('GET');
     }
     // Запомним последний запрос в виде строки
     $this->last_request = $this->client->getLastRequest();
     // Запомним последний запрос в виде Zend_Http_Response
     $this->last_response = $this->client->getLastResponse();
     return $this;
 }
コード例 #11
0
ファイル: StaticTest.php プロジェクト: alab1001101/zf2
 /**
  * Test that we properly calculate the content-length of multibyte-encoded
  * request body
  *
  * This may file in case that mbstring overloads the substr and strlen
  * functions, and the mbstring internal encoding is a multibyte encoding.
  *
  * @link http://framework.zend.com/issues/browse/ZF-2098
  */
 public function testMultibyteRawPostDataZF2098()
 {
     $this->_client->setAdapter('Zend\\Http\\Client\\Adapter\\Test');
     $this->_client->setUri('http://example.com');
     $bodyFile = __DIR__ . '/_files/ZF2098-multibytepostdata.txt';
     $this->_client->setRawBody(file_get_contents($bodyFile));
     $this->_client->setEncType('text/plain');
     $this->_client->setMethod('POST');
     $this->_client->send();
     $request = $this->_client->getLastRequest();
     if (!preg_match('/^content-length:\\s+(\\d+)/mi', $request, $match)) {
         $this->fail("Unable to find content-length header in request");
     }
     $this->assertEquals(filesize($bodyFile), (int) $match[1]);
 }
コード例 #12
0
 /**
  * 
  *
  * @param  $userId
  * @param  $attributes
  * @param  $spMetadata
  * @param  $idpMetadata
  * @return void
  */
 public function provisionUser($userId, $attributes, $spMetadata, $idpMetadata)
 {
     if (!$spMetadata['MustProvisionExternally']) {
         return;
     }
     // https://os.XXX.surfconext.nl/provisioning-manager/provisioning/jit.shtml?
     // provisionDomain=apps.surfnet.nl&provisionAdmin=admin%40apps.surfnet.nl&
     // provisionPassword=xxxxx&provisionType=GOOGLE&provisionGroups=true
     $client = new Zend_Http_Client($this->_url);
     $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('provisionType', $spMetadata['ExternalProvisionType'])->setParameterGet('provisionDomain', $spMetadata['ExternalProvisionDomain'])->setParameterGet('provisionAdmin', $spMetadata['ExternalProvisionAdmin'])->setParameterGet('provisionPassword', $spMetadata['ExternalProvisionPassword'])->setParameterGet('provisionGroups', $spMetadata['ExternalProvisionGroups'])->setRawData(json_encode($this->_getData($userId, $attributes)))->request('POST');
     $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], null);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: Sent HTTP request to provision user using " . __CLASS__, $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: URI: " . $client->getUri(true), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: REQUEST: " . $client->getLastRequest(), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: RESPONSE: " . $client->getLastResponse(), $additionalInfo);
 }
コード例 #13
0
 /**
  * Return a single record
  *
  * @param string $_id
  * @param $_getDeleted get deleted records
  * @return Tinebase_Record_Interface
  */
 public function get($_id, $_getDeleted = FALSE)
 {
     // get basics
     $this->_httpClient->resetParameters();
     $this->_httpClient->setUri($this->_config->rest->url . "/REST/1.0/ticket/" . $_id . "/show");
     $this->_httpClient->setMethod(Zend_Http_Client::GET);
     $response = $this->_httpClient->request();
     $ticket = $this->_rawDataToTicket($response->getBody());
     // get history
     $this->_httpClient->resetParameters();
     $this->_httpClient->setUri($this->_config->rest->url . "/REST/1.0/ticket/" . $_id . "/history");
     $this->_httpClient->setParameterGet('format', 'l');
     $this->_httpClient->setMethod(Zend_Http_Client::GET);
     $response = $this->_httpClient->request();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__FILE__ . '::' . __LINE__ . ' request :' . $this->_httpClient->getLastRequest());
     }
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__FILE__ . '::' . __LINE__ . ' response :' . $response->asString());
     $ticket->History = $this->_rawDataToHistory($response->getBody());
     return $ticket;
 }
コード例 #14
0
 /**
  * Add Super Tag
  * 
  * NOTE: Super Tags cannot be created via the API, so they need to be created via the HTML interface before you apply them 
  *
  * @param Kohana_Company $company
  * @param string $tag
  */
 public function addSuperTag(Kohana_Company $company, Kohana_SuperTag $tag)
 {
     $realTagName = str_replace(' ', '_', strtolower($tag->getName()));
     $reqUrl = 'https://' . $this->_account . '.batchbook.com/service/companies/' . $company->getId() . '/super_tags/' . $realTagName . '.xml';
     error_log('requrl:' . $reqUrl);
     $httpClient = new Zend_Http_Client($reqUrl);
     $paramsPut = array();
     $fields = $tag->getFields();
     foreach ($fields as $key => $value) {
         //keys must be lower case and have spaces replaced with underscore
         $realKey = str_replace(' ', '_', strtolower($key));
         $realValue = urlencode($value);
         error_log('realKey:' . $realKey);
         error_log('realValue:' . $realValue);
         $paramsPut['super_tag[' . strtolower($realKey) . ']'] = $value;
     }
     $httpClient->setAuth($this->_token, 'x');
     $httpClient->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
     $httpClient->setRawData(http_build_query($paramsPut, '', '&'), Zend_Http_Client::ENC_URLENCODED);
     $response = $httpClient->request(Zend_Http_Client::PUT);
     if (200 != $response->getStatus()) {
         //TODO: throw more specific exception
         throw new Exception('SuperTag \'' . $tag->getName() . '\' not added to Company with id=' . $company->getId() . "\n" . $response->getMessage() . "\n" . $response->getBody() . "\n" . $httpClient->getLastRequest());
     }
 }
コード例 #15
0
 /**
  * Debug helper function to log the last request/response pair against the DMS server
  *
  * @parma Zend_Http_Client $client Zend Http client object
  * @return void
  */
 private function _debugRequest(Zend_Http_Client $client)
 {
     $config = Zend_Registry::get('params');
     $logfile = '';
     // Capture DMS service parameters
     if (isset($config->dms) && isset($config->dms->logfile)) {
         $logfile = $config->dms->logfile;
     }
     if ($logfile != null && APPLICATION_ENV != 'production') {
         $request = $client->getLastRequest();
         $response = $client->getLastResponse();
         $fh = fopen($logfile, 'a+');
         fwrite($fh, $request);
         fwrite($fh, "\n\n");
         fwrite($fh, $response);
         fwrite($fh, "\n\n\n\n");
         fclose($fh);
     }
 }
コード例 #16
0
ファイル: Abstract.php プロジェクト: 7ochem/magento_extension
 protected function _call($endpoint, $params = null, $method = 'GET', $data = null, $silent = false, $global = false)
 {
     if ($params && is_array($params) && count($params) > 0) {
         $args = array();
         foreach ($params as $arg => $val) {
             $args[] = urlencode($arg) . '=' . urlencode($val);
         }
         $endpoint .= '?' . implode('&', $args);
     }
     $url = $this->_getUrl($endpoint);
     $method = strtoupper($method);
     $client = new Zend_Http_Client($url);
     $client->setMethod($method);
     $client->setHeaders(array('Accept' => 'application/json', 'Content-Type' => 'application/json'));
     $client->setAuth($this->getUsername(), $this->getPassword());
     if ($method == 'POST' || $method == "PUT") {
         $client->setRawData(json_encode($data), 'application/json');
     }
     Mage::log(print_r(array('url' => $url, 'method' => $method, 'data' => json_encode($data)), true), null, 'zendesk.log');
     try {
         $response = $client->request();
     } catch (Zend_Http_Client_Exception $ex) {
         Mage::log('Call to ' . $url . ' resulted in: ' . $ex->getMessage(), Zend_Log::ERR, 'zendesk.log');
         Mage::log('--Last Request: ' . $client->getLastRequest(), Zend_Log::ERR, 'zendesk.log');
         Mage::log('--Last Response: ' . $client->getLastResponse(), Zend_Log::ERR, 'zendesk.log');
         return array();
     }
     $body = json_decode($response->getBody(), true);
     Mage::log(var_export($body, true), Zend_Log::DEBUG, 'zendesk.log');
     if ($response->isError()) {
         if (is_array($body) && isset($body['error'])) {
             if (is_array($body['error']) && isset($body['error']['title'])) {
                 if (!$silent) {
                     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__($body['error']['title'], $response->getStatus()));
                     return;
                 } else {
                     return $body;
                 }
             } else {
                 if (!$silent) {
                     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__($body['error'], $response->getStatus()));
                     return;
                 } else {
                     return $body;
                 }
             }
         } else {
             if (!$silent) {
                 Mage::getSingleton('adminhtml/session')->addError(Mage::helper('zendesk')->__($body, $response->getStatus()));
                 return;
             } else {
                 return $body;
             }
         }
     }
     return $body;
 }
コード例 #17
0
ファイル: example.php プロジェクト: Tony133/zf-web
<?php

require_once 'Zend/Http/Client.php';
$uri = 'http://www.example.com/pan/aReport3Key.action?columns=orderNR&columns=orderValue';
echo "original uri: {$uri}\n";
$client = new Zend_Http_Client($uri);
$client->request();
echo "request made: " . $client->getLastRequest() . "\n";
コード例 #18
0
 /**
  * Put Deal
  *
  * @param Batchblue_Service_BatchBook_Deal $deal
  * @return Batchblue_Service_BatchBook_DealService   Provides a fluent interface
  */
 public function putDeal(Batchblue_Service_BatchBook_Deal $deal)
 {
     $httpClient = new Zend_Http_Client('https://' . $this->_accountName . '.batchbook.com/service/deals/' . $deal->getId() . '.xml');
     $paramsPut = array('deal[title]' => $deal->getTitle(), 'deal[description]' => $deal->getDescription(), 'deal[amount]' => $deal->getAmount(), 'deal[status]' => $deal->getStatus());
     $httpClient->setAuth($this->_token, 'x');
     $httpClient->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
     $httpClient->setRawData(http_build_query($paramsPut, '', '&'), Zend_Http_Client::ENC_URLENCODED);
     $response = $httpClient->request(Zend_Http_Client::PUT);
     if (200 != $response->getStatus()) {
         //TODO: throw more specific exception
         echo $httpClient->getLastRequest();
         throw new Exception('Deal not updated:' . $response->getMessage() . "\n" . $response->getBody());
     }
     return $this;
 }
コード例 #19
0
ファイル: S3.php プロジェクト: jorgenils/zend-framework
 /**
  * Make a request to Amazon S3
  *
  * @param  string $method
  * @param  string $path
  * @param  array $headers
  * @return Zend_Http_Response
  */
 private function _makeRequest($method, $path, $headers = array())
 {
     $retry_count = 0;
     if (!is_array($headers)) {
         $headers = array($headers);
     }
     // Strip off the beginning s3:// (assuming this is the scheme used)
     if (strpos($path, self::STREAM_ID) !== false) {
         $path = substr($path, 5);
     }
     do {
         $retry = false;
         $headers['Date'] = gmdate(DATE_RFC1123, time());
         self::addSignature($method, $path, $headers);
         $client = new Zend_Http_Client(self::S3_ENDPOINT . '/' . $path);
         $client->setHeaders($headers);
         if ($method == 'PUT' && $this->_objectBuffer !== null) {
             if (!isset($headers['Content-type'])) {
                 $headers['Content-type'] = self::getMimeType($path);
             }
             $client->setRawData($this->_objectBuffer, $headers['Content-type']);
         }
         $response = $client->request($method);
         if (self::$logger instanceof Zend_Log) {
             self::$logger->log($client->getLastRequest(), Zend_Log::INFO);
             Zend_Debug::dump($client->getLastResponse());
             //self::$logger->log($response, Zend_Log::INFO);
         }
         $response_code = $response->getStatus();
         // Some 5xx errors are expected, so retry automatically
         if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) {
             $retry = true;
             $retry_count++;
             if (self::$logger instanceof Zend_Log) {
                 self::$logger->log($response_code . ' : retrying ' . $method . ' request (' . $retry_count . ')', Zend_Log::INFO);
             }
             sleep($retry_count / 4 * $retry_count);
         } else {
             if ($response_code == 307) {
                 echo "We need to redirect";
             } else {
                 if ($response_code == 100) {
                     echo "OK to Continue";
                 }
             }
         }
     } while ($retry);
     return $response;
 }
コード例 #20
0
ファイル: client.php プロジェクト: biozshock/PHPProxifier
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: ";
// browsers keep this blank.
$http->setHeaders($header);
// POST, PUT
//$http->setParameterPost('data', '<PutTimeOffset>true</PutTimeOffset>');
//$http->setEncType(Zend_Http_Client::ENC_URLENCODED);
//$httpResponse = $http->request(Zend_Http_Client::POST);
//$httpResponse = $http->request(Zend_Http_Client::PUT);
//add a raw data if you want
//$http->setRawData('<PutTimeOffset>true</PutTimeOffset>', Zend_Http_Client::ENC_FORMDATA);
//delete
//$httpResponse = $http->request(Zend_Http_Client::DELETE);
//get
$httpResponse = $http->request(Zend_Http_Client::GET);
if (!$httpResponse->isSuccessful()) {
    print 'Error getting response';
}
// maybe you want to see whole request
if (false) {
    print $http->getLastRequest();
}
$responseHeaders = $httpResponse->getHeaders();
unset($responseHeaders['Content-encoding']);
unset($responseHeaders['Vary']);
foreach ($responseHeaders as $responseHeaderName => $responseHeaderValue) {
    header($responseHeaderName . ':' . $responseHeaderValue);
}
print $httpResponse->getBody();
コード例 #21
0
ファイル: all.php プロジェクト: robriggen/kohana-batchbook
 /**
  * Put ToDo
  *
  * @param Kohana_ToDo $todo
  * @return Kohana_ToDoService   Provides a fluent interface
  */
 public function putToDo(Kohana_ToDo $todo)
 {
     $httpClient = new Zend_Http_Client('https://' . $this->_accountName . '.batchbook.com/service/todos/' . $todo->getId() . '.xml');
     $paramsPut = array('todo[title]' => $todo->getTitle(), 'todo[description]' => $todo->getDescription(), 'todo[due_date]' => $todo->getDueDate(), 'todo[flagged]' => $todo->getFlagged(), 'todo[complete]' => $todo->getComplete());
     $httpClient->setAuth($this->_token, 'x');
     $httpClient->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
     $httpClient->setRawData(http_build_query($paramsPut, '', '&'), Zend_Http_Client::ENC_URLENCODED);
     $response = $httpClient->request(Zend_Http_Client::PUT);
     if (200 != $response->getStatus()) {
         //TODO: throw more specific exception
         echo $httpClient->getLastRequest();
         throw new Exception('ToDo not updated:' . $response->getMessage() . "\n" . $response->getBody());
     }
     return $this;
 }
コード例 #22
0
 /**
  * Make an AJAX request.
  *
  * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions
  * Additional options are:
  * 'document' - document for global events, @see phpQuery::getDocumentID()
  * 'referer' - implemented
  * 'requested_with' - TODO; not implemented (X-Requested-With)
  * @return Zend_Http_Client
  * @link http://docs.jquery.com/Ajax/jQuery.ajax
  *
  * @TODO $options['cache']
  * @TODO $options['processData']
  * @TODO $options['xhr']
  * @TODO $options['data'] as string
  * @TODO XHR interface
  */
 public static function ajax($options = array(), $xhr = null)
 {
     $options = array_merge(self::$ajaxSettings, $options);
     $documentID = isset($options['document']) ? self::getDocumentID($options['document']) : null;
     if ($xhr) {
         // reuse existing XHR object, but clean it up
         $client = $xhr;
         //			$client->setParameterPost(null);
         //			$client->setParameterGet(null);
         $client->setAuth(false);
         $client->setHeaders("If-Modified-Since", null);
         $client->setHeaders("Referer", null);
         $client->resetParameters();
     } else {
         // create new XHR object
         require_once 'Zend/Http/Client.php';
         $client = new Zend_Http_Client();
         $client->setCookieJar();
     }
     if (isset($options['timeout'])) {
         $client->setConfig(array('timeout' => $options['timeout']));
     }
     //			'maxredirects' => 0,
     foreach (self::$ajaxAllowedHosts as $k => $host) {
         if ($host == '.' && isset($_SERVER['HTTP_HOST'])) {
             self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST'];
         }
     }
     $host = parse_url($options['url'], PHP_URL_HOST);
     if (!in_array($host, self::$ajaxAllowedHosts)) {
         throw new Exception("Request not permitted, host '{$host}' not present in " . "phpQuery::\$ajaxAllowedHosts");
     }
     // JSONP
     $jsre = "/=\\?(&|\$)/";
     if (isset($options['dataType']) && $options['dataType'] == 'jsonp') {
         $jsonpCallbackParam = $options['jsonp'] ? $options['jsonp'] : 'callback';
         if (strtolower($options['type']) == 'get') {
             if (!preg_match($jsre, $options['url'])) {
                 $sep = strpos($options['url'], '?') ? '&' : '?';
                 $options['url'] .= "{$sep}{$jsonpCallbackParam}=?";
             }
         } else {
             if ($options['data']) {
                 $jsonp = false;
                 foreach ($options['data'] as $n => $v) {
                     if ($v == '?') {
                         $jsonp = true;
                     }
                 }
                 if (!$jsonp) {
                     $options['data'][$jsonpCallbackParam] = '?';
                 }
             }
         }
         $options['dataType'] = 'json';
     }
     if (isset($options['dataType']) && $options['dataType'] == 'json') {
         $jsonpCallback = 'json_' . md5(microtime());
         $jsonpData = $jsonpUrl = false;
         if ($options['data']) {
             foreach ($options['data'] as $n => $v) {
                 if ($v == '?') {
                     $jsonpData = $n;
                 }
             }
         }
         if (preg_match($jsre, $options['url'])) {
             $jsonpUrl = true;
         }
         if ($jsonpData !== false || $jsonpUrl) {
             // remember callback name for httpData()
             $options['_jsonp'] = $jsonpCallback;
             if ($jsonpData !== false) {
                 $options['data'][$jsonpData] = $jsonpCallback;
             }
             if ($jsonpUrl) {
                 $options['url'] = preg_replace($jsre, "={$jsonpCallback}\\1", $options['url']);
             }
         }
     }
     $client->setUri($options['url']);
     $client->setMethod(strtoupper($options['type']));
     if (isset($options['referer']) && $options['referer']) {
         $client->setHeaders('Referer', $options['referer']);
     }
     $client->setHeaders(array('User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko' . '/2008122010 Firefox/3.0.5', 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Language' => 'en-us,en;q=0.5'));
     if ($options['username']) {
         $client->setAuth($options['username'], $options['password']);
     }
     if (isset($options['ifModified']) && $options['ifModified']) {
         $client->setHeaders("If-Modified-Since", self::$lastModified ? self::$lastModified : "Thu, 01 Jan 1970 00:00:00 GMT");
     }
     $client->setHeaders("Accept", isset($options['dataType']) && isset(self::$ajaxSettings['accepts'][$options['dataType']]) ? self::$ajaxSettings['accepts'][$options['dataType']] . ", */*" : self::$ajaxSettings['accepts']['_default']);
     // TODO $options['processData']
     if ($options['data'] instanceof phpQueryObject) {
         $serialized = $options['data']->serializeArray($options['data']);
         $options['data'] = array();
         foreach ($serialized as $r) {
             $options['data'][$r['name']] = $r['value'];
         }
     }
     if (strtolower($options['type']) == 'get') {
         $client->setParameterGet($options['data']);
     } else {
         if (strtolower($options['type']) == 'post') {
             $client->setEncType($options['contentType']);
             $client->setParameterPost($options['data']);
         }
     }
     if (self::$active == 0 && $options['global']) {
         phpQueryEvents::trigger($documentID, 'ajaxStart');
     }
     self::$active++;
     // beforeSend callback
     if (isset($options['beforeSend']) && $options['beforeSend']) {
         phpQuery::callbackRun($options['beforeSend'], array($client));
     }
     // ajaxSend event
     if ($options['global']) {
         phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options));
     }
     if (phpQuery::$debug) {
         self::debug("{$options['type']}: {$options['url']}\n");
         self::debug("Options: <pre>" . var_export($options, true) . "</pre>\n");
         //			if ($client->getCookieJar())
         //				self::debug("Cookies: <pre>".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."</pre>\n");
     }
     // request
     $response = $client->request();
     if (phpQuery::$debug) {
         self::debug('Status: ' . $response->getStatus() . ' / ' . $response->getMessage());
         self::debug($client->getLastRequest());
         self::debug($response->getHeaders());
     }
     if ($response->isSuccessful()) {
         // XXX tempolary
         self::$lastModified = $response->getHeader('Last-Modified');
         $data = self::httpData($response->getBody(), $options['dataType'], $options);
         if (isset($options['success']) && $options['success']) {
             phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options));
         }
         if ($options['global']) {
             phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options));
         }
     } else {
         if (isset($options['error']) && $options['error']) {
             phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage()));
         }
         if ($options['global']) {
             phpQueryEvents::trigger($documentID, 'ajaxError', array($client, $response->getMessage(), $options));
         }
     }
     if (isset($options['complete']) && $options['complete']) {
         phpQuery::callbackRun($options['complete'], array($client, $response->getStatus()));
     }
     if ($options['global']) {
         phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options));
     }
     if ($options['global'] && !--self::$active) {
         phpQueryEvents::trigger($documentID, 'ajaxStop');
     }
     return $client;
     //		if (is_null($domId))
     //			$domId = self::$defaultDocumentID ? self::$defaultDocumentID : false;
     //		return new phpQueryAjaxResponse($response, $domId);
 }
コード例 #23
0
ファイル: Standard.php プロジェクト: albertobraschi/Quack-BB
 /**
  * @param array $params
  * @return Quack_BB_Model_Sonda
  */
 public function sonda($params)
 {
     $this->log("Quack_BB_Model_Standard::sonda() started");
     $client = new Zend_Http_Client($this->getSondaUrl());
     $client->setParameterPost($params);
     $result = $client->request('POST')->getBody();
     $this->log("URI: {$client->getLastRequest()}");
     $result = preg_replace('/<\\![^>]*>/', '', $result);
     // remove doctype and cdata declarations
     $result = preg_replace('/<\\?[^>]*>/', '', $result);
     // remove xml version and charset declaration
     $sonda = Mage::getModel('bb/sonda');
     /* @var $sonda Quack_BB_Model_Sonda */
     $xml = @simplexml_load_string($result);
     foreach ($xml->children() as $child) {
         $sonda->setDataUsingMethod($child['nome'], (string) $child['valor']);
     }
     $this->log($result);
     return $sonda;
 }