setAuth() public méthode

$type should be one of the supported types - see the self::AUTH_* constants. To enable authentication: $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC); To disable authentication: $this->setAuth(false);
See also: http://www.faqs.org/rfcs/rfc2617.html
public setAuth ( string | false $user, string $password = '', string $type = self::AUTH_BASIC ) : Zend_Http_Client
$user string | false User name or false disable authentication
$password string Password
$type string Authentication type
Résultat Zend_Http_Client
Exemple #1
0
 public function __construct($apiKey, $subdomain, Zend_Http_Client $client)
 {
     $this->apiKey = $apiKey;
     $this->client = $client;
     $this->subdomain = $subdomain;
     $this->client->setAuth($this->apiKey, 'X');
 }
 /**
  * Constructs a new Simpy (free) REST API Client
  *
  * @param  string $username Username for the Simpy user account
  * @param  string $password Password for the Simpy user account
  * @return void
  */
 public function __construct($username, $password)
 {
     /**
      * @see Zend_Service_Rest
      */
     require_once 'Zend/Rest/Client.php';
     $this->_http = new Zend_Http_Client();
     $this->_http->setAuth($username, $password);
 }
Exemple #3
0
 /**
  * the constructor
  *
  * don't use the constructor. use the singleton
  */
 private function __construct($_username, $_password, $_url)
 {
     $this->_url = empty($_url) ? 'https://samurai.sipgate.net/RPC2' : $_url;
     $this->_username = $_username;
     $this->_password = $_password;
     $this->_http = new Zend_Http_Client($this->_url);
     $this->_http->setMethod('post');
     $this->_http->setAuth($_username, $_password);
     $this->_rpc = new Zend_XmlRpc_Client($this->_url, $this->_http->setAuth($_username, $_password));
     $this->_rpc->call('samurai.ClientIdentify', array(0 => new Zend_XmlRpc_Value_Struct(array('ClientName' => new Zend_XmlRpc_Value_String('Tine 2.0 Sipgate'), 'ClientVersion' => new Zend_XmlRpc_Value_String('0.4'), 'ClientVendor' => new Zend_XmlRpc_Value_String('Alexander Stintzing')))));
 }
 /**
  * Execute CheddarGetter API request
  *
  * @param string $url Url to the API action
  * @param string $username Username
  * @param string $password Password
  * @param array|null $args HTTP post key value pairs
  * @return string Body of the response from the CheddarGetter API
  * @throws Zend_Http_Client_Exception A Zend_Http_Client_Exception may
  * be thrown under a number of conditions but most likely if the tcp socket
  * fails to connect.
  */
 public function request($url, $username, $password, array $args = null)
 {
     // reset
     $this->_client->setUri($url);
     $this->_client->resetParameters();
     $this->_client->setMethod(Zend_Http_Client::GET);
     $this->_client->setAuth($username, $password);
     if ($args) {
         $this->_client->setMethod(Zend_Http_Client::POST);
         $this->_client->setParameterPost($args);
     }
     $response = $this->_client->request();
     return $response->getBody();
 }
Exemple #5
0
 protected function _call($endpoint, $params = null, $method = 'GET', $data = null)
 {
     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(Mage::getStoreConfig('zendesk/general/email') . '/token', Mage::getStoreConfig('zendesk/general/password'));
     if ($method == 'POST') {
         $client->setRawData(json_encode($data), 'application/json');
     }
     Mage::log(print_r(array('url' => $url, 'method' => $method, 'data' => json_encode($data)), true), null, 'zendesk.log');
     $response = $client->request();
     $body = json_decode($response->getBody(), true);
     Mage::log(var_export($body, true), null, 'zendesk.log');
     if ($response->isError()) {
         if (is_array($body) && isset($body['error'])) {
             if (is_array($body['error']) && isset($body['error']['title'])) {
                 throw new Exception($body['error']['title'], $response->getStatus());
             } else {
                 throw new Exception($body['error'], $response->getStatus());
             }
         } else {
             throw new Exception($body, $response->getStatus());
         }
     }
     return $body;
 }
 public function icsAction()
 {
     $this->api_user = Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('pmt_api_user')->getValue('text');
     $this->api_password = Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('pmt_api_password')->getValue('text');
     // get prescription id
     $prescriptionRepeatId = Mage::app()->getRequest()->getParam('id');
     $customer = Mage::getSingleton('customer/session')->getCustomer();
     $client = new Zend_Http_Client($this->api_get_prescripton_url . $prescriptionRepeatId);
     $params = ['pmt_user_id' => $customer->getId(), 'prescription_repeat_id' => $prescriptionRepeatId];
     // set some parameters
     $client->setParameterPost($params);
     $client->setAuth($this->api_user, $this->api_password, \Zend_Http_Client::AUTH_BASIC);
     // POST request
     $result = $client->request(Zend_Http_Client::POST);
     // decode response
     $jsonData = json_decode($result->getBody());
     //		var_dump($prescriptionRepeatId . $customer->getId());
     //		var_dump($result);
     //		exit();
     if (!$jsonData->status == 'success') {
         // create error message, before redirecting
         // redirect to prescriptions page
         $this->redirectDashboard();
     }
     $this->loadLayout();
     $block = $this->getLayout()->getBlock('prescriptions_ics');
     $block->assign(['repeat' => $jsonData->data->repeats[0], 'product' => $jsonData->data->prescription]);
     $this->renderLayout();
 }
 public function mailgunRequest($type, $domain, $apiKey, $data, $method = Zend_Http_Client::GET, $uriOveride = false)
 {
     $client = new Zend_Http_Client();
     $client->setAuth("api", $apiKey);
     $client->setMethod($method);
     if ($uriOveride) {
         $client->setUri($uriOveride);
     } else {
         $client->setUri($this->apiUrl . $domain . "/" . $type);
     }
     if ($method == Zend_Http_Client::POST) {
         foreach ($data as $key => $value) {
             $client->setParameterPost($key, $value);
         }
     } else {
         foreach ($data as $key => $value) {
             $client->setParameterGet($key, $value);
         }
     }
     try {
         $response = $client->request();
         if ($response->getStatus() == 200) {
             return json_decode($response->getBody());
         } else {
             throw new Zend_Http_Exception("Error connecting to MailGun API. Returned error code: " . $response->getStatus() . " --- " . $response->getBody());
         }
     } catch (Exception $e) {
         Mage::logException($e);
         return false;
     }
 }
Exemple #8
0
    /**
     * Test setAuth (dynamic method) fails when trying to use an unsupported
     * authentication scheme
     *
     */
    public function testExceptUnsupportedAuthDynamic()
    {
        $this->setExpectedException(
            'Zend\Http\Client\Exception\InvalidArgumentException',
            'Invalid or not supported authentication type: \'SuperStrongAlgo\'');

        $this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo');
    }
 /**
  * Performs an HTTP POST request to $path.
  *
  * @param string $path
  * @param mixed $data Raw data to send
  * @throws Zend_Http_Client_Exception
  * @return Zend_Http_Response
  */
 protected function _post($path, $data = null)
 {
     $this->_prepare($path);
     if ($this->_authorizationCredentials) {
         $this->_localHttpClient->setAuth($this->getLogin() . "/token", $this->getToken());
     }
     return $this->_performPost('POST', $data);
 }
Exemple #10
0
 /**
  * Test setAuth (dynamic method) fails when trying to use an unsupported
  * authentication scheme
  *
  */
 public function testExceptUnsupportedAuthDynamic()
 {
     try {
         $this->client->setAuth('shahar', '1234', 'SuperStrongAlgo');
         $this->fail('Trying to use unknown authentication method, setAuth should throw an exception but it didn\'t');
     } catch (Zend_Http_Client_Exception $e) {
         // We're good!
     }
 }
Exemple #11
0
 /**
  * Initialize some of the basic properties.
  *
  * @return void
  */
 protected function init()
 {
     $config = Zend_Registry::getInstance()->config->watson;
     $client = new Zend_Http_Client();
     $client->setUri($config->baseUrl);
     $client->setAuth($config->username, $config->password, Zend_Http_Client::AUTH_BASIC);
     // Extra headers needed
     $client->setHeaders(array('X-SyncTimeout' => $config->timeout, 'Content-Type' => 'application/json', 'Accept' => 'application/json'));
     $this->_httpClient = $client;
 }
 /**
  * Test that we can unset HTTP authentication when credentials is specified in the URI
  *
  */
 public function testCancelAuthWithCredentialsInUri()
 {
     $uri = str_replace('http://', 'http://%s:%s@', $this->baseuri) . 'testHttpAuth.php';
     // Set auth and cancel it
     $this->client->setUri(sprintf($uri, 'alice', 'secret'));
     $this->client->setAuth(false);
     $res = $this->client->request();
     $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
     $this->assertNotContains('alice', $res->getBody(), "Body contains the user name, but it shouldn't");
     $this->assertNotContains('secret', $res->getBody(), "Body contains the password, but it shouldn't");
 }
Exemple #13
0
 /**
  * Test we can unset HTTP authentication
  *
  */
 public function testCancelAuth()
 {
     $this->client->setUri($this->baseuri . 'testHttpAuth.php');
     // Set auth and cancel it
     $this->client->setAuth('alice', 'secret');
     $this->client->setAuth(false);
     $res = $this->client->request();
     $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
     $this->assertNotContains('alice', $res->getBody(), "Body contains the user name, but it shouldn't");
     $this->assertNotContains('secret', $res->getBody(), "Body contains the password, but it shouldn't");
 }
 /**
  * send command
  *
  * @param string $_phoneAddress Address of the phone
  * @param array  $_params       command params
  */
 private function sendCommand($_phoneAddress, array $_params = array(), $_user = NULL, $_pass = NULL)
 {
     $_config = array('useragent' => 'PHP snom remote client (rev: 0.1)', 'keepalive' => false);
     $client = new Zend_Http_Client('http://' . $_phoneAddress . '/command.htm', $_config);
     $client->setAuth($_user, $_pass, Zend_Http_Client::AUTH_BASIC);
     $client->setParameterGet($_params);
     $response = $client->request('GET');
     if (!$response->isSuccessful()) {
         throw new Phone_Exception_Snom('HTTP request to ' . $_phoneAddress . ' failed');
     }
     return $response->getBody();
 }
 public static function createFromConfigs(Zend_Config $config, $userId)
 {
     $httpClient = new Zend_Http_Client();
     $httpClient->setAuth($config->auth->user, $config->auth->password);
     $openSocialRestClient = new OpenSocial_Rest_Client($httpClient);
     $provider = new self($config->id, $config->name, $openSocialRestClient);
     $provider->configurePreconditions($config);
     $provider->configureGroupFilters($config);
     $provider->configureGroupMemberFilters($config);
     $decoratedProvider = $provider->configureDecoratorChain($config);
     return $decoratedProvider;
 }
Exemple #16
0
 /**
  * Test we can properly use Basic HTTP authentication
  *
  */
 public function testHttpAuthBasic()
 {
     $this->client->setUri($this->baseuri . 'testHttpAuth.php');
     $this->client->setParameterGet(array('user' => 'alice', 'pass' => 'secret', 'method' => 'Basic'));
     // First - fail password
     $this->client->setAuth('alice', 'wrong');
     $res = $this->client->send();
     $this->assertEquals(401, $res->getStatusCode(), 'Expected HTTP 401 response was not recieved');
     // Now use good password
     $this->client->setAuth('alice', 'secret');
     $res = $this->client->send();
     $this->assertEquals(200, $res->getStatusCode(), 'Expected HTTP 200 response was not recieved');
 }
Exemple #17
0
 function iqsms($message, $phones, $config)
 {
     $ok = 0;
     foreach ($phones as $phone) {
         $client = new Zend_Http_Client('http://gate.iqsms.ru/send/?phone=' . rawurlencode($phone) . '&text=' . rawurlencode($message) . (@$config['sender'] ? '&sender=' . rawurlencode($config['sender']) : ''));
         $y = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOption('sms');
         $y = $y['iqsms'];
         $client->setAuth($y['login'], $y['password']);
         $response = $client->request('GET');
         if ($response->getStatus() == 200 && stripos($response->getBody(), 'accepted') !== false) {
             $ok++;
         }
     }
     return $ok;
 }
 /**
  * Request a bearer token from the API
  *
  * @param  Mage_Core_Model_Store $store
  * @return boolean|string
  */
 public function getBearerToken($store = null)
 {
     $client = new Zend_Http_Client($this->getApiUrl('oauth2/token'));
     $client->setAuth($this->getConsumerKey($store), $this->getConsumerSecret($store));
     $client->setHeaders('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
     $client->setParameterPost('grant_type', 'client_credentials');
     $response = $client->request(Zend_Http_Client::POST);
     if (!$response->isSuccessful()) {
         return false;
     }
     $body = Mage::helper('core')->jsonDecode($response->getBody());
     if (is_array($body) && isset($body['access_token'])) {
         return $body['access_token'];
     }
     return false;
 }
 /**
  * get solvency request
  *
  * @param Mage_Sales_Model_Quote $quote
  *
  * @return Zend_Http_Client
  */
 public function getSolvencyRequest(Mage_Sales_Model_Quote $quote)
 {
     if ($this->getConfig()->isTestmode()) {
         $url = $this->getConfig()->getTestUrl();
     } else {
         $url = $this->getConfig()->getLiveUrl();
     }
     $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => $this->getConfig()->getTimeout()));
     $request = new Netresearch_Buergel_Model_Validation_Solvency_Request($this->getAddress($quote), $quote);
     $request->setHelper($this->getHelper());
     $request->setConfig($this->getConfig());
     $client->setMethod(Zend_Http_Client::POST);
     $client->setAuth($this->getConfig()->getUserId(), $this->getConfig()->getPassword());
     $client->setParameterPost('eing_dat', '' . $request);
     return $client;
 }
 /**
  *	Constructor
  *
  *	Connect to the NOC-PS server
  *	@param string $server     IP-address of server (will use default if empty)
  *	@param string $user       Username
  *	@param string $password   Password
  *	@param string $logusername OPTIONAL: client username/id for logging purposes
  */
 function __construct($server = NOCPS_DEFAULT_SERVER, $user = NOCPS_DEFAULT_USERNAME, $password = NOCPS_DEFAULT_PASSWORD, $logusername = '')
 {
     if (!$server) {
         die("Please set the server, username and password in " . __FILE__);
     }
     $http = new Zend_Http_Client();
     $http->setAuth($user, $password);
     /* If the API is used in a website, include IP-address of client as X-forwarded-for header for logging purposes */
     if (isset($_SERVER["REMOTE_ADDR"])) {
         $http->setHeaders("X-Forwarded-For: " . (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] . ", " : "") . $_SERVER['REMOTE_ADDR']);
     }
     if ($logusername) {
         $http->setHeaders("X-Forwarded-For-User: {$logusername}");
     }
     $this->_client = new Zend_XmlRpc_Client("https://{$server}/xmlrpc.php", $http);
     $this->_proxy = $this->_client->getProxy('PXE_API');
 }
Exemple #21
0
 /**
  * Simple Get-Method for reading Documents from the DB.
  * @param	string		$url		URl to read from, including a trailing slash.
  * @param	string|TRUE	$revision	Revision of Document, TRUE returns the latest Revision.
  * @return	array		$documents	Array with the actual requested Documents.
  * @throws	Couchdb_Exception_Connection
  */
 public function getFromUri($url, $revision = TRUE)
 {
     $connecter = new Zend_Http_Client();
     if ($this->_config->getUsername() != NULL && $this->_config->getPassword() != NULL) {
         $connecter->setAuth($this->_config->getUsername(), $this->_config->getPassword());
     }
     $host = $this->_getHostString();
     $uri = $revision === TRUE ? $url : $url . '?rev=' . $revision;
     $document = $connecter->setUri($host . $uri)->request('GET');
     if (!$document->isSuccessful()) {
         $error = "Could not connect to URl: " . $host . $uri;
         if ($revision !== TRUE) {
             $error .= ". Also consider that your called revision was compacted away.";
         }
         throw new Couchdb_Exception_Connection($error);
     }
     $array = json_decode($document->getBody());
     return $array;
 }
 /**
  * Initialize the service
  *
  * @param Zend_Config|array $config
  */
 public function __construct($config)
 {
     // store a copy
     $this->_config = $config;
     if ($config instanceof Zend_Config) {
         $config = $config->toArray();
     }
     // set individual properties
     $this->_apiId = $config['api_id'];
     $this->_apiPassword = $config['api_password'];
     $this->_apiSecret = $config['api_secret'];
     $this->_format = strtolower($config['format']);
     // set up http client
     $this->_client = new Zend_Http_Client();
     /**
      * @todo should these be config options?
      */
     $this->_client->setConfig(array('maxredirects' => 0, 'timeout' => 30, 'keepalive' => TRUE, 'useragent' => 'Crucial_Service_ChargifyV2/1.0 (https://github.com/crucialwebstudio/Crucial_Service_Chargify)'));
     // username, password for http authentication
     $this->_client->setAuth($this->_apiId, $this->_apiPassword, Zend_Http_Client::AUTH_BASIC);
 }
 /**
  * Get client HTTP
  * @return Zend_Http_Client
  */
 public function getClient()
 {
     if (is_null($this->_client)) {
         //$credentials = $this->getApiUsername($storeId) . ':' . $this->getApiPassword($storeId);
         //adapter options
         $config = array('curloptions' => array(CURLOPT_FAILONERROR => false, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true));
         // ----------------------------------------------------------------------
         // init proxy if not empty
         // ----------------------------------------------------------------------
         $proxy_host = Mage::getStoreConfig('hipay/hipay_api/proxy_host', Mage::app()->getStore());
         // if host not empty, we use the proxy parameters
         if (!empty($proxy_host)) {
             $proxy_user = Mage::getStoreConfig('hipay/hipay_api/proxy_user', Mage::app()->getStore());
             $proxy_pass = Mage::getStoreConfig('hipay/hipay_api/proxy_pass', Mage::app()->getStore());
             $proxy_port = Mage::getStoreConfig('hipay/hipay_api/proxy_port', Mage::app()->getStore());
             // init config for cURL
             $config['curloptions'][CURLOPT_PROXYUSERPWD] = true;
             $config['curloptions'][CURLOPT_PROXY] = $proxy_host . ':' . $proxy_port;
             // if user and password not empty, we use the credentials
             if (!empty($proxy_user) && !empty($proxy_pass)) {
                 $config['curloptions'][CURLOPT_PROXYUSERPWD] = $proxy_user . ':' . $proxy_pass;
             }
         }
         // Mage::log($config, null, 'curl.log');
         // ----------------------------------------------------------------------
         try {
             //innitialize http client and adapter curl
             $adapter = Mage::getSingleton('hipay/api_http_client_adapter_curl');
             $this->_client = new Zend_Http_Client();
             //$adapter->setConfig($config);
             $this->_client->setConfig($config);
             $this->_client->setHeaders(array('Content-Type' => 'application/xml', 'Accept' => 'application/json'));
             $this->_client->setAuth($this->getApiUsername($this->getStoreId()), $this->getApiPassword($this->getStoreId()), Zend_Http_Client::AUTH_BASIC);
             $this->_client->setAdapter($adapter);
         } catch (Exception $e) {
             Mage::throwException($e);
         }
     }
     return $this->_client;
 }
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $url
  * @param Varien_Object $data
  * @param string $method
  * @return Varien_Object
  */
 public function request($url, $data = null, $method = 'GET')
 {
     $config = array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'timeout' => 120);
     $client = new Zend_Http_Client($url, $config);
     $client->setAuth($this->getApiToken());
     $client->setMethod($method);
     if (!$data) {
         $data = new Varien_Object();
     }
     if (in_array($method, array(Zend_Http_Client::POST, Zend_Http_Client::PUT, Zend_Http_Client::DELETE))) {
         // Fix: items[0] -> items[]
         $rawData = http_build_query($this->_parseArray($data));
         $rawData = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $rawData);
         $client->setRawData($rawData);
     } else {
         $client->setParameterGet($this->_parseArray($data));
     }
     $response = $client->request();
     $body = json_decode($response->getBody(), true);
     $result = $this->_parseObject($body);
     return $result;
 }
 /**
  * connects to request tracker
  *
  * @return void
  */
 protected function _connect()
 {
     if (!$this->_config->rest || $this->_config->rest->url) {
         throw new Tinebase_Exception_NotFound('Could not connect to RequestTracker: No REST url given!');
     }
     $config = array('url' => $this->_config->rest->url, 'useragent' => 'Tine 2.0 remote client (rv: 0.2)', 'keepalive' => true);
     $this->_httpClient = new Zend_Http_Client($this->_config->rest->url, $config);
     $this->_httpClient->setCookieJar();
     // login
     $this->_httpClient->setMethod(Zend_Http_Client::POST);
     $this->_httpClient->setUri($this->_config->rest->url . "/REST/1.0/ticket/");
     $loginName = Tinebase_Core::getUser()->accountLoginName;
     if ($this->_config->useCustomCredendials) {
         $this->_httpClient->setAuth($this->_config->customCredentials->{$loginName}->username, $this->_config->customCredentials->{$loginName}->password);
     } else {
         $credentialCache = Tinebase_Core::getUserCredentialCache();
         Tinebase_Auth_CredentialCache::getInstance()->getCachedCredentials($credentialCache);
         $this->_httpClient->setAuth(Tinebase_Core::getUser()->accountLoginName, $credentialCache->password);
     }
     $response = $this->_httpClient->request();
     if ($response->getStatus() != 200) {
         throw new Tinebase_Exception_Record_NotAllowed($response->getMessage(), $response->getStatus());
     }
 }
Exemple #26
0
 /**
  * Constructs a new Simpy (free) REST API Client
  *
  * @param  string $username Username for the Simpy user account
  * @param  string $password Password for the Simpy user account
  * @return void
  */
 public function __construct($username, $password)
 {
     $this->_http = new Zend_Http_Client();
     $this->_http->setAuth($username, $password);
 }
 public function addTag(Batchblue_Service_BatchBook_Communication $communication, $tag)
 {
     $paramsPut = array('tag' => $tag);
     $httpClient = new Zend_Http_Client('https://' . $this->_accountName . '.batchbook.com/service/communications/' . $communication->getId() . '/add_tag.xml');
     $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('Tag not added.');
     }
     return $this;
 }
 /**
  * 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);
 }
Exemple #29
0
 /**
  * Set HTTP authentication parameters
  *
  * $type should be one of the supported types - see the self::AUTH_*
  * constants.
  *
  * To enable authentication:
  * <code>
  * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
  * </code>
  *
  * To disable authentication:
  * <code>
  * $this->setAuth(false);
  * </code>
  *
  * @see http://www.faqs.org/rfcs/rfc2617.html
  * @param string|false $user User name or false disable authentication
  * @param string $password Password
  * @param string $type Authentication type
  * @return Default_Plugin_HttpBox
  * @throws Zend_Http_Client_Exception
  */
 function httpAuth($user, $password = '', $type = Zend_Http_Client::AUTH_BASIC)
 {
     $this->client->setAuth($user, $password, $type);
     return $this;
 }
Exemple #30
0
 /**
  * Test setAuth (dynamic method) fails when trying to use an unsupported
  * authentication scheme
  *
  * @expectedException Zend_Http_Client_Exception
  */
 public function testExceptUnsupportedAuthDynamic()
 {
     $this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo');
 }